使用 iText7 打开 PDF 时自动打开打印对话框

Open print dialog automatically when PDF opened, using iText7

我使用 iText7 生成 PDF,然后在新标签页中打开。

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "C:\temp\first-output2.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

用户的意图始终是打印,因此显示 PDF 并让他单击打印按钮很不方便。这就是为什么我想 在打开 PDF 时立即打开打印对话框

此解决方案无效

Open print dialog automatically when PDF opened, using iText

因为PdfAction.PRINTDIALOG在iText7中不存在

我还尝试了各种 JavaScript 无效的选项,例如

PdfAction action = PdfAction.createJavaScript("this.print(true);\r"); 

如何在页面加载后直接打开打印对话框?

要在文档打开时打开打印对话框,您需要使用 this.print(true); JavaScript 代码。

您可以通过以下方式在iText7中添加这样的操作:

PdfAction printAction = new PdfAction();
printAction.put(PdfName.S, PdfName.JavaScript);
printAction.put(PdfName.JS, new PdfString("this.print(true);\r"));
pdfDocument.getCatalog().setOpenAction(printAction);