PDFlib

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

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

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

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

エラーハンドリング

PDFlibプログラミングでエラーをトラップするためのサンプルプログラムです。

例1:errorpolicy パラメータを return とした場合。これは、PDFlib 関数がエラーを感知した際に、-1 (PHP では 0)を返すことを意味します。利用できないフォントをロードする際、load_font 関数は -1 (PHP では 0) を返します。関数からの戻り位置をチェックして、代わりに他のフォントをロードします。

例2:errorpolicy パラメータを exception とした場合。これは、PDFlib 関数がエラーを感知するとすぐに例外を送出することを意味します。エラーポリシーが return の場合には常に PDFlib 関数の戻り値をチェックする必要があります。errorpolicy が return にセットされている場合は、load_image の戻り値をチェックすることにより、存在しない場合にテキストを出力できます。


/*
 * Error handling:
 * Demonstrate different strategies with respect to exception handling.
 * 
 * Example 1: Set the "errorpolicy" parameter to "return". This means that a 
 * PDFlib function call will return with -1 (in PHP: 0) when an error condition
 * is detected. Try to load a font which is not available so that load_font()
 * will return with -1 (in PHP: 0). Check for that return value and load another
 * available font instead.
 * 
 * Example 2: Set the "errorpolicy" parameter to "exception". This means that
 * an exception will be thrown whenever a PDFlib function call fails. Change the
 * error policy to "return" every time you want to check the return value of a
 * particular PDFlib function call. Then, set the "errorpolicy" parameter to
 * "return" to check the return value of load_image(). If the image to be loaded
 * does not exist output a replacement text. 
 * 
 * Required software: PDFlib/PDFlib+PDI/PPS 9
 * Required data: none
 */
package com.pdflib.cookbook.pdflib.general;

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

public class error_handling
{
    public static void main (String argv[])
    {
        /* This is where the data files are. Adjust as necessary. */
        String searchpath = "../input";
        String outfile = "error_handling.pdf";
        String title = "Error Handling";

        pdflib p = null;
        int exitcode = 0;
        String imagefile = "unavailable.jpg";
        int font, image;

        try {
            p = new pdflib();

            p.set_option("searchpath={" + searchpath + "}");

            /* Use the "errorpolicy" parameter to define an appropriate error 
             * policy.
             * The default setting "errorpolicy=legacy" ensures compatibility to
             * earlier versions of PDFlib, where exceptions and error return values
             * are controlled by parameters and options such as fontwarning,
             * imagewarning, etc. This is only recommended for applications which
             * require source code compatibility with PDFlib 6.
             * 
             * With "errorpolicy=exception" an exception will be thrown when an
             * error condition is detected. However, the output document will be
             * unusable after an exception. This can be used for lazy programming
             * without any error conditionals at the expense of sacrificing the
             * output document even for problems which may be fixable by the
             * application.
             * 
             * With "errorpolicy=return" when an error condition is detected, the
             * respective function will return with a -1 (in PHP: 0) error value
             * regardless of any warning parameters or options. The application
             * developer must check the return value to identify problems, and must
             * react on the problem in whatever way is appropriate for the
             * application. This is the recommended approach since it allows a
             * unified approach to error handling.
             */
            
            /* ------------------------------------------------------------------
             * First example: 
             * Set the "errorpolicy" to "return" for all function calls.
             * This means we must check the return values of load_font() etc. for
             * -1 (in PHP: 0).
             * ------------------------------------------------------------------
             */
            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);

            /* Start page */
            p.begin_page_ext(0, 0, "width=a4.height height=a4.width");

            /*
             * Try to load a special font which might not be available.
             */
            font = p.load_font("MyFontName", "unicode", "");

            /* Check the return value of load_font() */
            if (font == -1) {
                /* font handle is invalid; find out what happened */
                String errmsg = p.get_errmsg();

                /* Try a different font */
                font = p.load_font("Helvetica", "unicode", "");

                /* font handle is also invalid; give up */
                if (font == -1) {
                    throw new Exception("Error: " + p.get_errmsg());
                }

                /* Output the error message to the PDF. This is not pretty 
                 * realistic but it is intended to show how you can proceed after
                 * a failed function call without having damaged the PDF.
                 */
                p.setfont(font, 20);
                p.fit_textline(errmsg, 50, 400, "");
            }


            /* -------------------------------------------------------------------
             * Second example: 
             * Set the "errorpolicy" to "exception". Change it to "return" only if
             * you want to check the return value of a particular function call.
             * -------------------------------------------------------------------
             */
            p.set_option("errorpolicy=exception");

            /* Output some descriptive text */
            p.setfont(font, 20);
            p.fit_textline("Error policy can be legal, exception, or return.",
                50, 500, "");
            
            /* Set the "errorpolicy" parameter  to "return" to check the return
             * value of load_image(). Then set the parameter back to "exception"
             * again. If the image to be loaded does not exist a replacement text
             * will be output. 
             * 
             * Alternatively, the "errorpolicy=return" option of load_image() can be
             * used which changes the error policy just for the respective function
             * call. Note that this option is correctly supported only by 
             * PDFlib 7.0.3 and above.
             */
            p.set_option("errorpolicy=return");

            /* Load the image */
            image = p.load_image("auto", imagefile, "");

            /* Set the "errorpolicy" parameter  to "exception" again */
            p.set_option("errorpolicy=exception");

            /* Output some replacement text if image is not available */
            if (image == -1) {
                p.setcolor("fillstroke", "rgb", 1, 0, 0, 0);
                int x=50, y=200, w=200, h=100;
                p.rect(x, y, w, h);
                p.stroke();
                p.setfont(font, 10);
                p.fit_textline("Replacement text for unavailable image", 
                    x + 5, y + 5, "boxsize={" + (w - 10) + " " + (h - 10) + "}");
            }
            else {
                /* Place the image */
                p.fit_image(image, 20, 20, "scale=0.5");
            }

            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)