我编写了使用传入的打印机名称和PDF网址打印PDF的代码。这是有效的,除非我传递一个包含中文字符的PDF,字符只是方框。 Unicode字体嵌入了PDF,所以理想情况下,我想以某种方式利用它。这是打印的代码:
PDDocument document = PDDocument.load(new URL(fileUrl));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printer);
PageFormat pageFormat = job.defaultPage();
Paper paper = pageFormat.getPaper();
Book pBook = new Book();
List allPages = document.getDocumentCatalog().getAllPages();
for (Object pdPage : allPages)
{
PDPage page = (PDPage) pdPage;
double width = page.findMediaBox().getWidth();
double height = page.findMediaBox().getHeight();
double margin = 0.0d;
paper.setSize(width, height);
paper.setImageableArea(margin, margin, width - (margin * 2), height - (margin * 2));
pageFormat.setOrientation(PageFormat.PORTRAIT);
pageFormat.setPaper(paper);
PageFormat validatePage = job.validatePage(pageFormat);
pBook.append(document.getPrintable(allPages.indexOf(pdPage)), validatePage);
job.setPageable(pBook);
}
job.setJobName(jobName);
job.print();
如您所见,我正在使用PDFBox(版本1.8.7)。我已经对此做了一些搜索,但我找不到任何有用的东西。但我确实找到了这个JIRA问题:https://issues.apache.org/jira/browse/PDFBOX-490
似乎可能在今年(2016年)发布的2.0版本中已经完成了。有一次,我尝试更新到最新版本,但有很多变化,我选择不这样做。
正在更新我唯一的选择吗?我能在1.8.7做什么吗?
谢谢!
答案 0 :(得分:1)
根据mkl的评论,我更新到版本2.0.3并且正确打印了中文字符。这是我的新代码,与我的旧代码进行比较,看看有什么必要更新:
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printer);
PageFormat pageFormat = job.defaultPage();
Paper paper = pageFormat.getPaper();
Book pBook = new Book();
PDDocument document = PDDocument.load(new URL(fileUrl).openStream()); // Needs to be a stream now
PDPageTree allPages = document.getPages(); // no getDocumentCatalog
for (Object pdPage : allPages)
{
PDPage page = (PDPage) pdPage;
double width = page.getMediaBox().getWidth(); // getMediaBox instead of find
double height = page.getMediaBox().getHeight(); // getMediaBox instead of find
double margin = 0.0d;
paper.setSize(width, height);
paper.setImageableArea(margin, margin, width - (margin * 2), height - (margin * 2));
pageFormat.setOrientation(PageFormat.PORTRAIT);
pageFormat.setPaper(paper);
PageFormat validatePage = job.validatePage(pageFormat);
pBook.append(new PDFPrintable(document), validatePage, document.getNumberOfPages()); // Completely different
}
job.setPageable(pBook); // Moved this out of the loop, just cause it only needs to be called once
job.setJobName(jobName);
job.print();