PDF印刷 - 完全ガイド
このチュートリアルでは、JavaとJPedalを使用してPDFファイルを印刷する方法を5つの簡単なステップで紹介します。これらの5つのステップにより、印刷の実行方法をより細かく制御できます。そのような詳細な制御が必要ない場合は、print example を使用して、わずか数行のコードでPDFファイルを印刷できます。
まず、PDFファイルを表すPdfDecoder オブジェクトが必要です。必要に応じて、フォント置換の設定も行う必要がある場合があります。
暗号化されたPDFファイルの印刷に関する重要な注意事項
パスワードが必要な場合は、setEncryptionPassword(String password)
でパスワードを設定するか、以下に示すメソッドではなくopenPdfFile(String filename, String password)
を使用してファイルを開く必要があります。
PdfDecoder decodePdf = new PdfDecoder(true); //Set to true as I don't want to render it to screen in this tutorial
try {
decodePdf.openPdfFile("inputFile.pdf");
FontMappings.setFontReplacements();
} catch (Exception e) {
//...
}
また、用紙サイズや印刷部数など、使用したい設定をプリンタに伝えるAttributeSetも必要です。このチュートリアルでは、JobName属性のみを使用します。
利用可能なさまざまな属性の詳細については、こちらをクリック してください。
PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
JobName jobName = new JobName("Example Print", null);
attributeSet.add(jobName);
PdfDecoder クラスには、異なるサイズの用紙に印刷するか、ページの回転方法など、印刷出力を調整するために呼び出すことができる多くのメソッドがあります。これらのメソッドの中で最もよく使用されるものを以下に示します。
decodePdf.setPrintAutoRotateAndCenter(true);
decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_FIT_TO_PRINTER_MARGINS);
decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE);
decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_REDUCE_TO_PRINTER_MARGINS);
decodePdf.setPagePrintRange(1, decodePdf.getPageCount());
設定した属性をサポートするJavaで利用可能なPrintServices のリストを見つけるには、次のコードが必要です。ここでは、プリンタ名をコンソールに出力しているだけです。
PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributeSet);
for(PrintService s : services) {
System.out.println(s.getName());
}
アクセスできるプリンタがわかったら、以下のように指定した名前の特定のPrintServiceを取得するために、これらの名前を使用できます。
PrintService printingDevice;
for(PrintService s : services) {
if(s.getName().equals("Microsoft XPS Document Writer")) {
printingDevice = s;
}
}
印刷可能なオブジェクトを作成するには、PdfBookオブジェクトを作成する必要があります(必要に応じて、attributesパラメータはnullでも構いません)。これは、印刷のためにSimpleDoc に渡されます。
PdfBook pdfBook = new PdfBook(decodePdf, printingDevice, attributeSet);
SimpleDoc doc = new SimpleDoc(pdfBook, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
ここで必要なのは、PrintService からDocPrintJob を受け取り、SimpleDoc と属性(ある場合)をメソッドの入力変数として使用してPrintServiceのprintメソッドを呼び出すことだけです。
DocPrintJob printJob = printingDevice.createPrintJob();
try {
printJob.print(doc, attributeSet);
} catch (PrintException e) {
//...
}
これらのチュートリアルでは、JavaソフトウェアにPDF印刷機能を簡単に追加し、JPedalでカスタマイズする方法を紹介します。
