本教程介绍如何使用 Java 将 PDF 打印为 PDF。它包含设置 IDE 以使用 Aspose.PDF for Java 使用Java 虚拟 PDF 打印机打印 PDF 文件的所有详细信息。它将通过设置各种参数来帮助您配置输出 PDF 文件。
使用 Java 打印到 PDF 打印机的步骤
- 设置环境以使用 Aspose.PDF for Java 打印为 PDF
- 创建 PdfViewer 对象以加载源 PDF 文件
- 设置自动调整大小、自动旋转和隐藏打印对话框的属性
- 创建 PdfPrinterSettings 对象来设置软打印机名称
- 创建 PrintPageSettings 对象来定义输出 PDF 纸张大小和边距
- 调用 printDocumentWithSettings() 方法将加载的 PDF 打印到 PDF
按照以下步骤使用 Java 中的 PDF 打印机。创建 PdfViewer 类对象以加载源 PDF 文件,将标志设置为自动调整大小、自动旋转并隐藏打印页面对话框。创建 PdfPrinterSettings 和 PrintPageSettings 对象,并在调用 printDocumentWithSettings() 方法之前设置 PDF 打印机名称、纸张大小和边距。
使用 Java 打印到 PDF 虚拟打印机的代码
import com.aspose.pdf.*; | |
import com.aspose.pdf.facades.PdfViewer; | |
import com.aspose.pdf.printing.*; | |
public class Main | |
{ | |
public static void main(String[] args) throws Exception // PDF to PDF printing in Java | |
{ | |
// Set the licenses | |
new License().setLicense("License.lic"); | |
// Create PdfViewer object to load the PDF, set flags, and print the document | |
PdfViewer pdfViewer = new PdfViewer(); | |
pdfViewer.bindPdf("sample.pdf"); | |
pdfViewer.setAutoResize(true); | |
pdfViewer.setAutoRotate(true); | |
pdfViewer.setPrintPageDialog(false); | |
// Create objects for printer and page settings and PrintDocument | |
PdfPrinterSettings ps = new PdfPrinterSettings(); | |
PrintPageSettings pps = new PrintPageSettings(); | |
ps.setPrinterName("Adobe PDF"); | |
// Set paper size and margins | |
pps.setPaperSize(new PrintPaperSize("A4", 827, 1169)); | |
pps.setMargins(new PrinterMargins(2, 2, 2, 2)); | |
// Print PDF to PDF | |
pdfViewer.printDocumentWithSettings(pps, ps); | |
pdfViewer.close(); | |
System.out.println("Printing to PDF done successfully"); | |
} | |
} |
此代码演示了如何使用 Adobe PDF 打印机和 Java。此代码将显示用于输入输出 PDF 文件名的对话框。设置输出 PDF 名称后,加载的 PDF 将被打印为 PDF 并保存在磁盘上。
本文教我们如何使用Adobe PDF 虚拟打印机和 Java。如果您想插入分页符,请参阅 使用 Java 在 PDF 中插入分页符 上的文章。