【发布时间】:2018-10-19 14:49:23
【问题描述】:
我一直在尝试将 PDF 转换为具有透明度的 png 文件,但没有成功。 我试图用很多方法解决它,但我没有成功。 我正在写我的方式,希望有人能找到问题所在:
1.
try (final PDDocument document = PDDocument.load(new File(srcpath))){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
String fileName = imageConverted;
boolean hasAlpha = bim.getColorModel().hasAlpha();
System.out.println(hasAlpha);
ImageIOUtil.writeImage(bim, fileName, 300);
}
document.close();
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
-
RandomAccessFile raf; 尝试 { raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); // draw the first page to an image int num=pdffile.getNumPages(); for(int i=0;i<num;i++) { PDFPage page = pdffile.getPage(i); //get the width and height for the doc at the default zoom int width=(int)page.getBBox().getWidth(); int height=(int)page.getBBox().getHeight(); Rectangle rect = new Rectangle(0,0,width,height); int rotation=page.getRotation(); Rectangle rect1=rect; if(rotation==90 || rotation==270) rect1=new Rectangle(0,0,rect.height,rect.width); //generate the image BufferedImage img = (BufferedImage)page.getImage( rect.width, rect.height, //width & height rect1, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); Graphics2D graphics = (Graphics2D)img.getGraphics(); graphics.setBackground( new Color( 255, 255, 255, 0 ) ); ImageIO.write(img, "png", new File(imageConverted)); } } catch (FileNotFoundException e1) { System.err.println(e1.getLocalizedMessage()); } catch (IOException e) { System.err.println(e.getLocalizedMessage()); }
3.
// Instantiating the PDFRenderer class
PDFRenderer renderer = new PDFRenderer(document);
// Rendering an image from the PDF document
BufferedImage image = null;
try {
image= renderer.renderImage(0);
} catch (IOException e1) {
return "N/A";
}
// Writing the image to a file
try {
ImageIO.write(image, "png", new File(imageConverted));
} catch (IOException e) {
return "N/A";
}
但我得到的是白色背景的 png ...... 任何想法? 提前谢谢!!!
【问题讨论】:
-
尝试将
ImageType.RGB更改为ImageType.RGBA。 -
有效!!谢谢!!我应该把它改成 RGBA