繁体   English   中英

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

[英]How to add .png images to pdf using Apache PDFBox

当我尝试使用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();
        }
    }
}

有一个非常好的实用程序类PDImageXObject来从java.io.File加载图像。 据我所知,它适用于jpg和png文件。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM