图片转pdf,没用上,白写了一段代码,记录一下,为以后备用
加入依赖
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.24</version> </dependency>
测试代码
public class TestConvert { static { System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); } public static void main(String[] args) throws IOException { File file = new File("/Users/master/convert/852710016d2e4c7db.png"); PDDocument document = new PDDocument(); PDPage my_page = new PDPage(PDRectangle.A4); document.addPage(my_page); PDPage page = document.getPage(0); PDImageXObject pdImage = PDImageXObject.createFromFileByContent(file, document); PDPageContentStream contentStream = new PDPageContentStream(document, page); float height = page.getMediaBox().getHeight(); float width = page.getMediaBox().getWidth(); float imageHeight = pdImage.getHeight(); float imageWight = pdImage.getWidth(); if (imageHeight > imageWight) { float v = imageHeight / height; float h = imageWight / width; if (v > h) { float actWidth = width * (imageHeight / imageWight); contentStream.drawImage(pdImage, (width - actWidth) /2, 0, actWidth, height); } else { float actHeight = height * (imageWight / imageHeight); contentStream.drawImage(pdImage, 0, (height - actHeight)/2, width, actHeight); } } else { float actHeight = width * (imageHeight / imageWight); contentStream.drawImage(pdImage, 0, (height - actHeight) / 2, width, actHeight); } contentStream.setHorizontalScaling(200); contentStream.close(); document.save("/Users/master/convert/a.pdf"); document.close(); } }