以编程方式或使用对话框打印文档

本文介绍如何使用Aspose.WordsAPI打印文字处理文档。 它还演示了使用设置、打印预览和打印进度对话框打印文档的方法。

使用设置和打印预览对话框打印文档

处理文档时,通常需要将它们打印到选定的打印机。 使用打印预览对话框直观地检查打印文档的显示方式并选择相关的打印选项是很有帮助的。

Aspose.Words没有内置对话框或表单,但实现了AsposeWordsPrintDocument类复盖了两个java。啊打印出来。可打印和java。啊打印出来。可分页。

下面的示例演示如何使用这些类通过打印预览和设置对话框从Aspose.Words打印文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
PrinterJob pj = PrinterJob.getPrinterJob();
// Initialize the Print Dialog with the number of pages in the document.
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(new PageRanges(1, doc.getPageCount()));
if (!pj.printDialog(attributes)) {
return;
}
// This object is responsible for rendering our document for use with the Java
// Print API.
AsposeWordsPrintDocument awPrintDoc = new AsposeWordsPrintDocument(doc);
// Pass our document as pageable to the printer job.
pj.setPageable(awPrintDoc);
// Create an instance of the print preview dialog and pass the print dialog and
// our document.
// Note that AsposeWordsPrintDocument implements both the Pageable and Printable
// interfaces. If the pageable constructor for PrintPreviewDialog
// is used then the formatting of each page is taken from the document. If the
// printable constructor is used then Page Setup dialog becomes enabled
// and the desired page setting for all pages can be chosen there instead.
PrintPreviewDialog previewDlg = new PrintPreviewDialog(awPrintDoc);
// Pass the desired page range attributes to the print preview dialog.
previewDlg.setPrinterAttributes(attributes);
// Proceed with printing if the user accepts the print preview.
if (previewDlg.display())
pj.print(attributes);

在一张纸上打印多页

Aspose.Words实现MultipagePrintDocument类,通过定义文档在打印页面上显示的方式来微调打印操作以实现自定义逻辑。 MultipagePrintDocument类提供了在一张纸上打印多页的能力.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Create a print job to print our document with.
PrinterJob pj = PrinterJob.getPrinterJob();
// Initialize an attribute set with the number of pages in the document.
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(new PageRanges(1, doc.getPageCount()));
// Pass the printer settings along with the other parameters to the print document.
MultipagePrintDocument awPrintDoc = new MultipagePrintDocument(doc, 4, true, attributes);
// Pass the document to be printed using the print job.
pj.setPrintable(awPrintDoc);
pj.print();

您可以从以下位置下载使用MultipagePrintDocument类的示例 Aspose.Words GitHub.

此代码示例的结果如下所示:

print_several_pages_on_one_sheet_aspose_words_java/