圖片轉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(); } }