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