java pdfbox 單張圖片轉pdf


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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM