これはなに?

作成するPDF

pdf.png

pom.xml

iText の配布元の設定に従う。日本語を出力するために itext-asian もインストールする

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.snail.exam</groupId>
    <artifactId>PrintExam</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>PrintExam</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>itextpdf.com</id>
            <name>Maven Repository for iText</name>
            <url>http://maven.itextpdf.com/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>
</project>

プログラム

package com.snail.exam.printexam;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Hello world!
 *
 */
public class ITextExam {

    /** 横書き指定. */
    private static final String HORIZONTAL = "UniJIS-UCS2-H";
    /** 縦書き指定. */
    private static final String VERTICAL = "UniJIS-UCS2-V";
    /** 横書き指定 & 英数を半角幅で印字. */
    private static final String HORIZONTAL_HW = "UniJIS-UCS2-HW-H";
    /** 縦書き指定 & 英数を半角幅で印字. */
    private static final String VERTICAL_HW = "UniJIS-UCS2-HW-V";
    /** 平成明朝体. */
    private static final String MINCHO = "HeiseiMin-W3";
    /** 平成角ゴシック体. */
    private static final String GOTHIC = "HeiseiKakuGo-W5";

    public static void main(String[] args) {
        try {

            OutputStream out = new FileOutputStream("/tmp/iTextExample.pdf");

            // 1. Create Document
            //
            // Paper Size    : A4
            // Document Body : (50pt,50pt)-(540pt,792pt)
            //                 (Not include the header and the footer)
            //
            // cf . 1pt = 1/72.27 inch = 0.3514 mm
            //       A4 = (210mm x 297mm) = (595pt x 842pt)
            //
            Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter pdfwriter = PdfWriter.getInstance(doc, out);

            // 2. Footer And Header
            //
            // set box area including header and footer.
            Rectangle pageSize = doc.getPageSize();
            pdfwriter.setBoxSize(
                    "art", // cf.http://www.prepressure.com/pdf/basics/page_boxes
                    new Rectangle(
                    36, 50,
                    pageSize.getWidth() - 50,
                    pageSize.getHeight() - 36));

            // print header and fotter each when page end.
            pdfwriter.setPageEvent(new PdfPageEventHelper() {

                private Font fHeader = new Font(
                        BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                        10, Font.NORMAL);
                private Font fPage = new Font(
                        BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                        10, Font.NORMAL);

                @Override
                public void onEndPage(PdfWriter writer, Document document) {
                    Rectangle rect = writer.getBoxSize("art");
                    int pageNumber = writer.getPageNumber();
                    if ((pageNumber % 2) == 0) {
                        Phrase header = new Phrase("Southland Shipbuild Guild LTD");
                        header.setFont(fHeader);
                        ColumnText.showTextAligned(
                                writer.getDirectContent(),
                                Element.ALIGN_RIGHT,
                                header,
                                rect.getRight(),
                                rect.getTop(),
                                0);
                    } else {
                        Phrase header = new Phrase("Southland Shipbuild Guild LTD");
                        header.setFont(fHeader);
                        ColumnText.showTextAligned(
                                writer.getDirectContent(),
                                Element.ALIGN_LEFT,
                                header,
                                rect.getLeft(),
                                rect.getTop(),
                                0);
                    }

                    Phrase page = new Phrase(String.format("- %d -",
                            writer.getPageNumber()));
                    page.setFont(fPage);

                    ColumnText.showTextAligned(
                            writer.getDirectContent(),
                            Element.ALIGN_CENTER,
                            page,
                            (rect.getLeft() + rect.getRight()) / 2,
                            rect.getBottom(),
                            0);
                }
            });

            // 3. Print Body
            doc.open();

            // 3.1. Line and Text

            // The coordinate syste of PDF is same as math. Not as CG.
            // The Left-Bottom side is (0,0). And the Right-Top side is (595,842).
            PdfContentByte cb = pdfwriter.getDirectContent();

            cb.setLineWidth(2f);
            cb.setLineCap(PdfContentByte.LINE_CAP_ROUND);
            int y = (int) (doc.getPageSize().getHeight() * 0.66f);
            int left = 50;
            int right = (int) (doc.getPageSize().getWidth()) - 50;

            cb.moveTo(left, y);
            cb.lineTo(right, y);
            cb.stroke();

            cb.beginText();
            BaseFont fTitle = BaseFont.createFont(MINCHO, HORIZONTAL,
                    BaseFont.NOT_EMBEDDED);
            cb.setFontAndSize(fTitle, 40);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Quoting Price", (left
                    + right) / 2, y, 0);
            cb.endText();

            // 3.2. Document and Table
            doc.newPage();

            Font fBody = new Font(
                    BaseFont.createFont(MINCHO, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.NORMAL);

            Font fRed = new Font(
                    BaseFont.createFont(MINCHO, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.UNDERLINE);
            fRed.setColor(BaseColor.RED);

            doc.add(new Paragraph("Dear Ms. Elizabeth,", fBody));
            doc.add(new Paragraph(
                    "Thank you for requesting a quote for our products. "
                    + "We truly believe this quote will offer you the best value. "
                    + "The quotation is detailed as below.", fBody));

            // Table
            PdfPTable table = new PdfPTable(4);
            table.setSpacingBefore(20);
            table.getDefaultCell().setPadding(5);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.setWidthPercentage(80f);
            table.setWidths(new int[]{40, 20, 20, 20});

            Font fTblBold = new Font(
                    BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.BOLD);
            Font fTblThin = new Font(
                    BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.NORMAL);

            for (String tblHeader : new String[]{"Model", "QTY", "Unit Price", "TotalPrice}"}) {
                PdfPCell cell = new PdfPCell(new Phrase(tblHeader, fTblBold));
                cell.setGrayFill(0.8f);
                cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }

            for (String[] row : new String[][]{
                        {"Ship of the line (戦列艦)", "13", "£1,000", "£13,000"},
                        {"Frigate (フリゲート艦)", "36", "£500", "£18,000"},
                        {"Auxiliary Sloep (特務艦)", "3", "£750", "£2,250"},}) {

                for (int colNum = 0; colNum < row.length; colNum++) {
                    PdfPCell cell = new PdfPCell(new Phrase(row[colNum], fTblThin));
                    if (colNum == 0) {
                        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    } else {
                        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                    }
                    table.addCell(cell);
                }
            }

            PdfPCell cellTotalLabel = new PdfPCell(new Phrase("Total", fTblBold));
            cellTotalLabel.setGrayFill(0.8f);
            cellTotalLabel.setColspan(3);
            cellTotalLabel.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cellTotalLabel);

            PdfPCell cellTotalValue = new PdfPCell(new Phrase("£33,250", fTblBold));
            cellTotalValue.setGrayFill(0.8f);
            cellTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cellTotalValue);

            doc.add(table);


            doc.add(new Paragraph(
                    "\n"
                    + "Payment Terms: Pre-paid\n"
                    + "Payment Method: Gold / Government Bond (Need the Fooger Bank Guarantee)\n\n"
                    + "The items will be shipped within 3 month after receipt of the payment.", fBody));
            doc.add(new Paragraph(
                    "This quotation will expire on May 31, 1588.", fRed));
            doc.add(new Paragraph(
                    "If you have any questions, please let us know. We look forward to receiving your order.\n"
                    + "Thank you.\n\n"
                    + "Sincerely,\n\n"
                    + "Guilliam Boonen\n"
                    + "Sales Manager\n", fBody));

            // Document End
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

直接印刷する

作成した PDF を javax.print.DocPrinterJob で直接プリンタに送る。たいていのプリンタで使えそうだ。

package com.snail.exam.printexam;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.GraphicsConfiguration;
import java.io.ByteArrayOutputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.ResolutionSyntax;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaName;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrintQuality;
import javax.print.attribute.standard.PrinterResolution;

/**
 * Hello world!
 *
 */
public class ITextExam2 {

    /** 横書き指定. */
    private static final String HORIZONTAL = "UniJIS-UCS2-H";
    /** 縦書き指定. */
    private static final String VERTICAL = "UniJIS-UCS2-V";
    /** 横書き指定 & 英数を半角幅で印字. */
    private static final String HORIZONTAL_HW = "UniJIS-UCS2-HW-H";
    /** 縦書き指定 & 英数を半角幅で印字. */
    private static final String VERTICAL_HW = "UniJIS-UCS2-HW-V";
    /** 平成明朝体. */
    private static final String MINCHO = "HeiseiMin-W3";
    /** 平成角ゴシック体. */
    private static final String GOTHIC = "HeiseiKakuGo-W5";

    public static void main(String[] args) {
        try {

            //OutputStream out = new FileOutputStream("/tmp/iTextExample.pdf");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            
            // 1. Create Document
            //
            // Paper Size    : A4
            // Document Body : (50pt,50pt)-(540pt,792pt)
            //                 (Not include the header and the footer)
            //
            // cf . 1pt = 1/72.27 inch = 0.3514 mm
            //       A4 = (210mm x 297mm) = (595pt x 842pt)
            //
            Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter pdfwriter = PdfWriter.getInstance(doc, out);

            // 2. Footer And Header
            //
            // set box area including header and footer.
            Rectangle pageSize = doc.getPageSize();
            pdfwriter.setBoxSize(
                    "art", // cf.http://www.prepressure.com/pdf/basics/page_boxes
                    new Rectangle(
                    36, 50,
                    pageSize.getWidth() - 50,
                    pageSize.getHeight() - 36));

            // print header and fotter each when page end.
            pdfwriter.setPageEvent(new PdfPageEventHelper() {

                private Font fHeader = new Font(
                        BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                        10, Font.NORMAL);
                private Font fPage = new Font(
                        BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                        10, Font.NORMAL);

                @Override
                public void onEndPage(PdfWriter writer, Document document) {
                    Rectangle rect = writer.getBoxSize("art");
                    int pageNumber = writer.getPageNumber();
                    if ((pageNumber % 2) == 0) {
                        Phrase header = new Phrase("Southland Shipbuild Guild LTD");
                        header.setFont(fHeader);
                        ColumnText.showTextAligned(
                                writer.getDirectContent(),
                                Element.ALIGN_RIGHT,
                                header,
                                rect.getRight(),
                                rect.getTop(),
                                0);
                    } else {
                        Phrase header = new Phrase("Southland Shipbuild Guild LTD");
                        header.setFont(fHeader);
                        ColumnText.showTextAligned(
                                writer.getDirectContent(),
                                Element.ALIGN_LEFT,
                                header,
                                rect.getLeft(),
                                rect.getTop(),
                                0);
                    }

                    Phrase page = new Phrase(String.format("- %d -",
                            writer.getPageNumber()));
                    page.setFont(fPage);

                    ColumnText.showTextAligned(
                            writer.getDirectContent(),
                            Element.ALIGN_CENTER,
                            page,
                            (rect.getLeft() + rect.getRight()) / 2,
                            rect.getBottom(),
                            0);
                }
            });

            // 3. Print Body
            doc.open();

            // 3.1. Line and Text

            // The coordinate syste of PDF is same as math. Not as CG.
            // The Left-Bottom side is (0,0). And the Right-Top side is (595,842).
            PdfContentByte cb = pdfwriter.getDirectContent();

            cb.setLineWidth(2f);
            cb.setLineCap(PdfContentByte.LINE_CAP_ROUND);
            int y = (int) (doc.getPageSize().getHeight() * 0.66f);
            int left = 50;
            int right = (int) (doc.getPageSize().getWidth()) - 50;

            cb.moveTo(left, y);
            cb.lineTo(right, y);
            cb.stroke();

            cb.beginText();
            BaseFont fTitle = BaseFont.createFont(MINCHO, HORIZONTAL,
                    BaseFont.NOT_EMBEDDED);
            cb.setFontAndSize(fTitle, 40);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Quoting Price", (left
                    + right) / 2, y, 0);
            cb.endText();

            // 3.2. Document and Table
            doc.newPage();

            Font fBody = new Font(
                    BaseFont.createFont(MINCHO, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.NORMAL);

            Font fRed = new Font(
                    BaseFont.createFont(MINCHO, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.UNDERLINE);
            fRed.setColor(BaseColor.RED);

            doc.add(new Paragraph("Dear Ms. Elizabeth,", fBody));
            doc.add(new Paragraph(
                    "Thank you for requesting a quote for our products. "
                    + "We truly believe this quote will offer you the best value. "
                    + "The quotation is detailed as below.", fBody));

            // Table
            PdfPTable table = new PdfPTable(4);
            table.setSpacingBefore(20);
            table.getDefaultCell().setPadding(5);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.setWidthPercentage(80f);
            table.setWidths(new int[]{40, 20, 20, 20});

            Font fTblBold = new Font(
                    BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.BOLD);
            Font fTblThin = new Font(
                    BaseFont.createFont(GOTHIC, HORIZONTAL, BaseFont.NOT_EMBEDDED),
                    10, Font.NORMAL);

            for (String tblHeader : new String[]{"Model", "QTY", "Unit Price", "TotalPrice}"}) {
                PdfPCell cell = new PdfPCell(new Phrase(tblHeader, fTblBold));
                cell.setGrayFill(0.8f);
                cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }

            for (String[] row : new String[][]{
                        {"Ship of the line (戦列艦)", "13", "£1,000", "£13,000"},
                        {"Frigate (フリゲート艦)", "36", "£500", "£18,000"},
                        {"Auxiliary Sloep (特務艦)", "3", "£750", "£2,250"},}) {

                for (int colNum = 0; colNum < row.length; colNum++) {
                    PdfPCell cell = new PdfPCell(new Phrase(row[colNum], fTblThin));
                    if (colNum == 0) {
                        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    } else {
                        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                    }
                    table.addCell(cell);
                }
            }

            PdfPCell cellTotalLabel = new PdfPCell(new Phrase("Total", fTblBold));
            cellTotalLabel.setGrayFill(0.8f);
            cellTotalLabel.setColspan(3);
            cellTotalLabel.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cellTotalLabel);

            PdfPCell cellTotalValue = new PdfPCell(new Phrase("£33,250", fTblBold));
            cellTotalValue.setGrayFill(0.8f);
            cellTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cellTotalValue);

            doc.add(table);


            doc.add(new Paragraph(
                    "\n"
                    + "Payment Terms: Pre-paid\n"
                    + "Payment Method: Gold / Government Bond (Need the Fooger Bank Guarantee)\n\n"
                    + "The items will be shipped within 3 month after receipt of the payment.", fBody));
            doc.add(new Paragraph(
                    "This quotation will expire on May 31, 1588.", fRed));
            doc.add(new Paragraph(
                    "If you have any questions, please let us know. We look forward to receiving your order.\n"
                    + "Thank you.\n\n"
                    + "Sincerely,\n\n"
                    + "Guilliam Boonen\n"
                    + "Sales Manager\n", fBody));

            // Document End
            doc.close();
            
                        // ドキュメントの形式を設定
            DocFlavor myFormat = DocFlavor.BYTE_ARRAY.PDF;

            // Docオブジェクトの生成
            Doc myDoc = new SimpleDoc(out.toByteArray(), myFormat, null);

            // プリンタの検索条件 兼 印刷パラメータを構築 (A4 600x600dpi以上)
            // (解像度は印刷時に「最高」を指定し直す)
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(new Copies(1));
            aset.add(MediaName.ISO_A4_WHITE);
            aset.add(OrientationRequested.PORTRAIT);
            //aset.add(new PrinterResolution(600, 600, ResolutionSyntax.DPI));

            // 属性セットに従って印刷ができるプリンタを発見する
            PrintService[] services = PrintServiceLookup.lookupPrintServices(
                    myFormat, aset);

            // 最初に見つかったプリントサービスを使う
            if (services.length > 0) {
                PrintService ps = ServiceUI.printDialog(null, 50, 50, services, services[0], myFormat, aset);
                if (ps == null) {
                    return;    //キャンセルされた場合
                }

                DocPrintJob job = ps.createPrintJob();

                // 最高品位印刷をプリンタに指示
                aset.add(PrintQuality.HIGH);
                job.print(myDoc, aset);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

補遺


Java#Print


添付ファイル: filepdf.png 3138件 [詳細] fileiTextExample.pdf 3267件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2012-04-23 (月) 01:13:13 (4579d)
Short-URL: http://at-sushi.com/pukiwiki/index.php?cmd=s&k=9165aa30f0
ISBN10
ISBN13
9784061426061