如何使用Apache PDFBox将.png图像添加到PDF中

13

我尝试使用pdfBox绘制png图像时,页面仍然是空白的。是否有办法使用pdfBox插入png图像?

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

1
你向我们展示了代码。但问题是什么? - mkl
2
当我尝试绘制PNG图像时,页面保持空白,我的问题是是否有使用pdfBox插入PNG图像的方法... - user3404729
2
这个问题将在即将发布的1.8.5版本中得到解决,详情请见http://issues.apache.org/jira/browse/PDFBOX-2030。在2.0版本中(具有不同的API),该问题已经得到了解决,请见http://issues.apache.org/jira/browse/PDFBOX-1990。您可以从svn获取两个版本。 - Tilman Hausherr
@user3404729 我必须由衷地感谢您这段代码。 - Don Cheadle
1
这里有什么问题吗? - william.eyidi
我甚至无法添加一个 .jpg 文件,这是我得到的异常:2020-01-30 15:03:14,536 ERROR [at.home.digest.web.ExposeBean] (default task-4) Error creating Expose PDF file : javax.imageio.IIOException: Not a JPEG file: starts with 0x89 0x50 at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method) at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:731) at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly - Alex Mi
1个回答

6

有一个非常好用的实用类PDImageXObject可以从java.io.File中加载图像。据我所知,它可以很好地处理jpg和png文件。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接