PDFlib

高度なPDFアプリケーションの開発を支援する定番プログラムライブラリー Supported by インフォテック株式会社

PDFlib サンプル集(クックブック)

本サンプルプログラムは、PDF 文書生成ライブラリーの実装である PDFlib の基本的な機能を実際のプログラムで紹介したものです。

本サイトでダウンロードした PDFlib は、一部機能の制限を除き、評価版として無償でお使いいただけます。

現在のテキスト位置の取得

PDFlib で、簡単なテキスト、テキスト行、テキストフローを出力して現在のテキスト位置を取得するサンプルプログラムです。

ページ上にテキストを出力する位置を set_text_pos 関数を用いて設定します。show 関数を使うと、簡単なテキストを出力できます。テキスト位置は、出力されたテキストの最後に移動されます。get_value 関数に textx および texty を指定することで、現在のテキスト位置が取得できます。fit_textline を使って基本的な行テキストを出力します。テキストフローによる出力で、現在のテキスト位置は、テキスト行の下に配置されます。したがって、現在のテキスト位置は、テキストフローの終りに位置し、Z線を出力します。


/*
 * Current text position:
 * Demonstrate how the current text position can be used to output simple text,
 * text lines, or Textflows next to one another.
 * 
 * Use set_text_pos() to set the position for text output on the page. 
 * Output some simple text using show(). The text position will be implicitly
 * moved at the end of the output text. 
 * Use get_option() with "textx" and "texty" to retrieve the current text
 * position.
 * Based on these values output a text line using fit_textline(). 
 * Output a Textflow at the current text position below the text line. 
 * Retrieve the current text position at the end of the Textflow and output a Z
 * line there. 
 *
 * Required software: PDFlib/PDFlib+PDI/PPS 9
 * Required data: none
 */
package com.pdflib.cookbook.pdflib.textflow;

import com.pdflib.pdflib;
import com.pdflib.PDFlibException;

public class current_text_position
{
    public static void main (String argv[])
    {
        pdflib p = null;

        String outfile = "current_text_position.pdf";
        String title = "Current Text Position";
        int i, tf = -1, font, fsize = 12;
        String result;
        final double llx=150, lly=50, urx=330, ury=700;
        double textx, texty;
        int exitcode = 0;
       

        /* Repeat the dummy text to produce more contents */
        final int count = 3;

        final String optlist1 =
            "fontname=Helvetica fontsize=" + fsize + " encoding=unicode " +
            "fillcolor={gray 0} alignment=justify";

        final String optlist2 =
            "fontname=Helvetica-Bold fontsize=14 encoding=unicode " +
            "fillcolor={rgb 1 0 0} charref";

        /* Dummy text for filling the columns. Soft hyphens are marked with the
         * character reference "­" (character references are enabled by the
         * charref option).
         */
        final String text = 
            "Lorem ipsum dolor sit amet, consectetur adi­pi­sicing elit, " +
            "sed do eius­mod tempor incidi­dunt ut labore et dolore " +
            "magna ali­qua. Ut enim ad minim ve­niam, quis nostrud " +
            "exer­citation ull­amco la­bo­ris nisi ut " +
            "ali­quip ex ea commodo con­sequat. Duis aute irure dolor " +
            "in repre­henderit in voluptate velit esse cillum dolore eu " +
            "fugiat nulla pari­atur. Excep­teur sint occae­cat " +
            "cupi­datat non proident, sunt in culpa qui officia " +
            "dese­runt mollit anim id est laborum. ";

        try {
            p = new pdflib();

            /* This means we must check return values of load_font() etc. */
            p.set_option("errorpolicy=return");

            if (p.begin_document(outfile, "") == -1)
                throw new Exception("Error: " + p.get_errmsg());

            p.set_info("Creator", "PDFlib Cookbook");
            p.set_info("Title", title);
            
            /* Load font */
            font = p.load_font("Helvetica-Bold", "unicode", "");

            if (font == -1)
                throw new Exception("Error: " + p.get_errmsg());
            
            p.begin_page_ext(0, 0, "width=a4.width height=a4.height");
            
            p.setfont(font, fsize);
            p.setcolor("fillstroke", "rgb", 1, 0, 0, 0);
            
            
            /* ------------------------------------------------------------------
             * Use simple text output functions for text output. The current text
             * position is moved to the end of the output text.
             * ------------------------------------------------------------------
             */
            
            /* Set the position for text output on the page */
            p.set_text_pos(llx, ury + 50);
            
            /* Output text at the current text position */
            p.show("LORE IPSUM ");
            
            /* Output text at the end of the preceding text */
            p.show("DOLOR SIT AMET,");
            
            /* Retrieve the current text position */
            textx = p.get_option("textx", "");
            texty = p.get_option("texty", "");
            
            /* Output text while setting the current text position to about one
             * line below
             */
            p.show_xy("CONSECTETUR", llx, texty -= (fsize*1.2));
            
            /* -----------------------------------------------------
             * Output a text line based on the current text position
             * ----------------------------------------------------- 
             */
            p.fit_textline("ADIPISICING ELIT...", llx, (texty -= fsize*1.2), "");
            
            
            /* -----------------------------------------------------------------
             * Output a Textflow and use the current text position at the end of
             * the Textflow to stroke some lines
             * -----------------------------------------------------------------
             */
            
            /* Create some amount of dummy text and feed it to a Textflow
             * object with alternating options.
             */
            for (i=1; i<=count; i++)
            {
                String num = i + " ";

                tf = p.add_textflow(tf, num, optlist2);
                if (tf == -1)
                    throw new Exception("Error: " + p.get_errmsg());

                tf = p.add_textflow(tf, text, optlist1);
                if (tf == -1)
                    throw new Exception("Error: " + p.get_errmsg());
            }
            
            /* Retrieve the current text position */
            textx = p.get_option("textx", "");
            texty = p.get_option("texty", "");
            
            texty -= 30;

            /* Loop until all of the text is placed. "_boxfull" means we must
             * continue because there is more text
             */
            do {
                String optlist = "verticalalign=justify linespreadlimit=120% ";
                result = p.fit_textflow(tf, llx, lly, urx, texty, optlist);
            } while (result.equals("_boxfull"));
            
            /* Draw a Z line after the Textflow if the Textflow has been placed
             * correctly 
             */
            if (result.equals("_stop")) {
                /* Get the current text position at the end of the Textflow */
                textx = p.get_option("textx", "");
                texty = p.get_option("texty", "");
                
                /* Stroke Z line at the end of the Textflow */
                p.setcolor("stroke", "rgb", 1, 0, 0, 0);
                p.setlinewidth(2);
                          
                texty += 4;
                p.moveto(textx, texty);
                p.lineto(urx, texty);
                p.lineto(llx, lly);
                p.lineto(urx, lly);
                p.stroke();
            }

            /* Check for errors */
            else {
                /* "_boxempty" happens if the box is very small and doesn't
                 * hold any text at all.
                 */
                if (result.equals("_boxempty"))
                    throw new Exception ("Error: Textflow box too small");
                else
                {
                    /* Any other return value is a user exit caused by
                     * the "return" option; this requires dedicated code to
                     * deal with.
                     */
                    throw new Exception ("User return '" + result +
                            "' found in Textflow");
                }
            }

            p.delete_textflow(tf);
            
            p.end_page_ext("");

            p.end_document("");

        } catch (PDFlibException e) {
            System.err.println("PDFlib exception occurred:");
            System.err.println("[" + e.get_errnum() + "] " + e.get_apiname()
                + ": " + e.get_errmsg());
            exitcode = 1;
        } catch (Exception e) {
            System.err.println(e);
            exitcode = 1;
        } finally {
            if (p != null) {
                p.delete();
            }
            System.exit(exitcode);
        }
    }
}
(Apr 3, 2007 - May 23, 2019)