我正在处理一个用户故事,要求能够将所有现有的打印输出为PDF。为此,我将java.awt.Printable
渲染为BufferedImage
,并使用Apache的PDFBox将此图像放入PDF中,但我使用此方法遇到了一些问题:
PDJPeg
,图像会变得模糊。PDPixelMap
,则生成的PDF格式为黑色。我能想到的唯一另一种方法是创建一个接口,即Printer
,然后创建两个子类,即PhysicalPrinter
和PDFPrinter
,但这需要我重新实现所有现有的java.awt.Printable
使用这个新界面。
这是我当前打印到PDF方法的SSCCE:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg;
public class Printer {
private Printer() {}
public static boolean printToPDF(String file, Printable printable) {
try {
PageFormat pageFormat = new PageFormat();
PDDocument doc = new PDDocument();
int width = (int)(pageFormat.getWidth());
int height = (int)(pageFormat.getHeight());
int currentPage = 0;
while(true) {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.BLACK);
g2d.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
if(printable.print(g2d, pageFormat, currentPage) == Printable.NO_SUCH_PAGE) {
break;
}
ImageIO.write(image, "png", new File("test.png"));
PDPage page = new PDPage();
doc.addPage(page);
PDJpeg img = new PDJpeg(doc, image); //Blurry
//PDPixelMap img = new PDPixelMap(doc, image); //Black
PDPageContentStream content = new PDPageContentStream(doc, page);
content.drawImage(img, 0, 0);
content.close();
++currentPage;
}
doc.save(file);
doc.close();
} catch(Exception e) {
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
Printable printable = new Printable() {
@Override
public int print(Graphics g, PageFormat pf, int index)
throws PrinterException {
if(index > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
Random rand = new Random();
for(int i = 0; i < 30; ++i) {
int x = rand.nextInt((int)pf.getImageableWidth());
int y = rand.nextInt((int)pf.getImageableHeight());
g2d.drawString("Test", x, y);
}
return PAGE_EXISTS;
}
};
printToPDF("Test.pdf", printable);
}
}
修改
我设法解决了黑色PDPixelMap
,使用错误的图像类型将其归结为BUfferedImage
。我将其从BufferedImage.TYPE_INT_RGB
更改为BufferedImage.TYPE_4BYTE_ABGR
。不幸的是,结果PDF仍然模糊不清。
答案 0 :(得分:0)
我认为可能对您有帮助的两个框架是IText和PDFRenderer。 IText是免费的4.2版本(如果我没记错的话),PDFRenderer是LGPL 2.1许可证。例如,最好查看教程,这些教程在网上很多。我认为两者都是您想要实现的目标的可行解决方案。我个人使用PDFRenderer。