Java 如何使用 Apache PDFBox 将 .png 图像添加到 pdf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22317706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add .png images to pdf using Apache PDFBox
提问by user3404729
When I try to draw png images using pdfBox, the pages remain blank. Is there any way to insert png images using 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();
}
}
}
回答by Kai
There is a pretty nice utility class PDImageXObjectto load Images from a java.io.File. As far as I know, it works well with jpg and png files.
有一个非常好的实用程序类PDImageXObject可以从 java.io.File 加载图像。据我所知,它适用于 jpg 和 png 文件。
PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, doc);
contentStream.drawImage(pdImage, 20f, 20f);