Today, I would like to show you how to print a Word document in Java. There are three ways to do it with Spire.doc for Java:
.
Now, let me introduce each of them.
1. From the official website of E-iceblue Free Spire.doc for Java Download the free version.
2. Start the IDE, create a new project, and then add the appropriate Spire.doc.jar for the installed files to your references.
public static void main(String[] args) throws Exception {
//Load the Document.
Document doc = new Document();
doc.loadFromFile("Sample.docx");
PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
PageFormat loPageFormat = loPrinterJob.defaultPage();
//Set the paper size.
Paper loPaper = loPageFormat.getPaper();
loPaper.setSize(600, 500);
loPageFormat.setPaper(loPaper);
//Remove the default margin.
loPaper.setImageableArea(0, 0, loPageFormat.getWidth(), loPageFormat.getHeight());
//Set the number of copies to print.
loPrinterJob.setCopies(1);
loPrinterJob.setPrintable(doc, loPageFormat);
//Set the dialog box.
if (loPrinterJob.printDialog()) {
//Print.
try {
loPrinterJob.print();
} catch (PrinterException e)
{
e.printStackTrace();
}
}
}
}
<h4> Print to a physical printer </h4>
```java
import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;
public class PrintWord {
public static void main(String[] args) {
//Load Word.
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");
//Create a PrinterSettings object.
PrinterSettings printerSettings = new PrinterSettings();
//Set the name of the physical printer.
printerSettings.setPrinterName("\\\\192.168.1.104\\HP LaserJet P1007");
//Set the number of copies to print.
printerSettings.setCopies((short) 1);
//Set the print range.
printerSettings.setFromPage(2);
printerSettings.setToPage(4);
//Apply the settings.
document.getPrintDocument().setPrinterSettings(printerSettings);
//Print.
document.getPrintDocument().print();
}
}
public class PrintWord {
public static void main(String[] args) {
//Load Word.
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocumentToPrint.docx");
//Create a PrinterSettings object.
PrinterSettings printerSettings = new PrinterSettings();
//Set up a virtual printer.
printerSettings.setPrinterName("Microsoft Print to PDF");
//Print to a file.
printerSettings.setPrintToFile(true);
//Set the save location and name of the file.
printerSettings.setPrintFileName("output/PrintToPDF.pdf");
//Apply the settings.
document.getPrintDocument().setPrinterSettings(printerSettings);
//Print.
document.getPrintDocument().print();
}
}
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20201216/20201216122015.png " alt="f:id:lendoris:20201216122015p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p><br /><br /></p>
<p> </p>
Recommended Posts