如何使用 Apache PDFBox 将 .png 图像添加到 pdf [英] How to add .png images to pdf using Apache PDFBox

查看:42
本文介绍了如何使用 Apache PDFBox 将 .png 图像添加到 pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用 pdfBox 绘制 png 图像时,页面保持空白.有没有办法用pdfBox插入png图片?

When I try to draw png images using pdfBox, the pages remain blank. Is there any way to insert png images using pdfBox?

public void createPDFFromImage( String inputFile, String image, String outputFile ) 
        throws IOException, COSVisitorException
{
    // the document
    PDDocument doc = null;
    try
    {
        doc = PDDocument.load( inputFile );

        //we will add the image to the first page.
        PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );

        PDXObjectImage ximage = null;
        if( image.toLowerCase().endsWith( ".jpg" ) )
        {
            ximage = new PDJpeg(doc, new FileInputStream( image ) );
        }
        else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
        {
            ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
        }
        else
        {
            BufferedImage awtImage = ImageIO.read( new File( image ) );
            ximage = new PDPixelMap(doc, awtImage);
  //          throw new IOException( "Image type not supported:" + image );
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
        contentStream.drawImage( ximage, 20, 20 );
        contentStream.close();
        doc.save( outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}

推荐答案

有一个很不错的实用类 PDImageXObject 从 java.io.File 加载图像.据我所知,它适用于 jpg 和 png 文件.

There is a pretty nice utility class PDImageXObject to load Images from a java.io.File. As far as I know, it works well with jpg and png files.

PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, doc);
contentStream.drawImage(pdImage, 20f, 20f); 

这篇关于如何使用 Apache PDFBox 将 .png 图像添加到 pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆