Create PDF from a PNG image Or Java Panel

萝らか妹 提交于 2019-12-19 04:15:25

问题


I'm looking for a Java library that will can take a Image (PNG) and create a PDF. Or Create the PDF directly from a java panel that has been drawn.


回答1:


You can achieve this using Gnostice PDFOne for Java (http://www.gnostice.com/PDFOne_Java.asp).

Find below the code snippet that creates a PDF document from a PNG image.

PdfDocument doc = new PdfDocument();

// Read the image as BufferedImage object
BufferedImage bufImg = ImageIO.read(new File(
    "SampleImage.PNG"));

// Create PdfImage object using the above BufferedImage object
PdfImage img = PdfImage.create(bufImg);

// Create a PdfPage of image size (image width x image Height)
PdfPage page1 = new PdfPage(img.width(), img.height());

// draw the image at 0, 0
page1.drawImage(img, 0, 0);

// add the page to the document object
doc.add(page1);

// save the document to the output file
doc.save("PNGImageToPDF.pdf");
doc.close();

To create a BufferedImage from a JPanel you can use the below code snippet.

int w = jpanel.getWidth();
int h = jpanel.getHeight();
BufferedImage bi = new BufferedImage(w, h,
    BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
jpanel.paint(g2);
g2.dispose();

After creating BuffereImage from JPanel you can use the first code snippet to create PDF.

I hope you will find this useful.

Disclaimer: I work for Gnostice.




回答2:


Try xsPDF:

BufferedImage image = ImageIO.read(new File(imageFileName));
int width = image.getWidth(), height = image.getHeight();
XSPDF.getInstance()
.setPageSize(width, height)
.setPageMargin(NO_MARGIN)
.setImage(image, 0, 0, width, height, 0)
.createPdf(pdfFileName);


来源:https://stackoverflow.com/questions/10466569/create-pdf-from-a-png-image-or-java-panel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!