Я пытался преобразовать 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 = новый RandomAccessFile (файл, "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 с белым фоном ...
Любая идея?
Заранее спасибо !!!