Example usage for com.itextpdf.text.pdf BaseFont EMBEDDED

List of usage examples for com.itextpdf.text.pdf BaseFont EMBEDDED

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf BaseFont EMBEDDED.

Prototype

boolean EMBEDDED

To view the source code for com.itextpdf.text.pdf BaseFont EMBEDDED.

Click Source Link

Document

if the font has to be embedded

Usage

From source file:org.ganttproject.impex.htmlpdf.fonts.TTFontCache.java

License:Open Source License

protected BaseFont getFallbackFont(String charset) {
    if (myFallbackFont == null) {
        try {/*  w  ww.j a v a  2s  .  co m*/
            myFallbackFont = BaseFont.createFont(
                    Platform.resolve(getClass().getResource(FALLBACK_FONT_PATH)).getPath(), charset,
                    BaseFont.EMBEDDED);
        } catch (DocumentException e) {
            GPLogger.logToLogger(e);
        } catch (IOException e) {
            GPLogger.logToLogger(e);
        }
    }
    return myFallbackFont;
}

From source file:org.qnot.passtab.PDFOutput.java

License:Open Source License

public PDFOutput(boolean withColor) {
    this.withColor = withColor;

    try {//from   www  .j  ava  2 s. co m
        font = new Font(BaseFont.createFont(PDFOutput.FONT_MONOSPACE, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
        fontBold = new Font(
                BaseFont.createFont(PDFOutput.FONT_MONOSPACE_BOLD, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
    } catch (Exception e) {
        try {
            font = new Font(BaseFont.createFont());
            fontBold = new Font(BaseFont.createFont());
        } catch (Exception ignored) {
        }
    }

    font.setSize(DEFAULT_FONT_SIZE);
    fontBold.setSize(DEFAULT_FONT_SIZE);
}

From source file:org.smap.sdal.managers.MiscPDFManager.java

License:Open Source License

public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletResponse response, int o_id, int month, int year, String period, String org_name) {

    PreparedStatement pstmt = null;

    if (org_name == null) {
        org_name = "None";
    }/* ww w . j a  va 2s  .com*/

    try {

        String filename;

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        filename = org_name + "_" + year + "_" + month + ".pdf";

        /*
         * Get the usage results
         */
        String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and extract(month from upload_time) = ? " // current month
                + "and extract(year from upload_time) = ? " // current year
                + "and ue.user_name = users.ident) as month, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? "
                + "and not users.temporary " + "order by users.ident;";

        pstmt = sd.prepareStatement(sql);
        pstmt.setInt(1, month);
        pstmt.setInt(2, year);
        pstmt.setInt(3, o_id);
        log.info("Get Usage Data: " + pstmt.toString());

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf";
        File stationaryFile = new File(stationaryName);

        ByteArrayOutputStream baos = null;
        ByteArrayOutputStream baos_s = null;
        PdfWriter writer = null;

        /*
         * Create document in two passes, the second pass adds the letter head
         */

        // Create the underlying document as a byte array
        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);

        if (stationaryFile.exists()) {
            baos = new ByteArrayOutputStream();
            baos_s = new ByteArrayOutputStream();
            writer = PdfWriter.getInstance(document, baos);
        } else {
            writer = PdfWriter.getInstance(document, outputStream);
        }

        writer.setInitialLeading(12);
        writer.setPageEvent(new PageSizer());
        document.open();

        // Write the usage data
        ResultSet resultSet = pstmt.executeQuery();

        PdfPTable table = new PdfPTable(4);

        // Add the header row
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("User Id");
        table.addCell("User Name");
        table.addCell("Usage in Period");
        table.addCell("All Time Usage");

        table.setHeaderRows(1);

        // Add the user data
        int total = 0;
        int totalAllTime = 0;

        table.getDefaultCell().setBackgroundColor(null);
        while (resultSet.next()) {
            String ident = resultSet.getString("ident");
            String name = resultSet.getString("name");
            String monthUsage = resultSet.getString("month");
            int monthUsageInt = resultSet.getInt("month");
            String allTime = resultSet.getString("all_time");
            int allTimeInt = resultSet.getInt("all_time");

            table.addCell(ident);
            table.addCell(name);
            table.addCell(monthUsage);
            table.addCell(allTime);

            total += monthUsageInt;
            totalAllTime += allTimeInt;

        }

        // Add the totals
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("Totals: ");
        table.addCell(" ");
        table.addCell(String.valueOf(total));
        table.addCell(String.valueOf(totalAllTime));

        document.add(table);
        document.close();

        if (stationaryFile.exists()) {

            // Step 2 - Populate the fields in the stationary
            PdfReader s_reader = new PdfReader(stationaryName);
            PdfStamper s_stamper = new PdfStamper(s_reader, baos_s);
            AcroFields pdfForm = s_stamper.getAcroFields();
            Set<String> fields = pdfForm.getFields().keySet();
            for (String key : fields) {
                log.info("Field: " + key);
            }

            pdfForm.setField("billing_period", period);
            pdfForm.setField("organisation", org_name);

            s_stamper.setFormFlattening(true);
            s_stamper.close();

            // Step 3 - Apply the stationary to the underlying document
            PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document
            PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1);
            int n = reader.getNumberOfPages();
            PdfContentByte background;
            for (int i = 0; i < n; i++) {
                background = stamper.getUnderContent(i + 1);
                if (i == 0) {
                    background.addTemplate(letter1, 0, 0);
                }
            }

            stamper.close();
            reader.close();

        }

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }

}

From source file:org.smap.sdal.managers.MiscPDFManager.java

License:Open Source License

public void createTasksPdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletRequest request, HttpServletResponse response, int tgId) {

    try {/*from  w  ww .j a  v  a2 s. c om*/

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        /*
         * Get the tasks for this task group
         */
        String urlprefix = request.getScheme() + "://" + request.getServerName();
        TaskManager tm = new TaskManager(localisation, tz);
        TaskListGeoJson t = tm.getTasks(sd, urlprefix, 0, tgId, 0, false, 0, null, "all", 0, 0, "scheduled",
                "desc");
        PdfWriter writer = null;

        String filename = "tasks.pdf";
        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            setFilenameInResponse(filename, response);
        }

        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
        writer = PdfWriter.getInstance(document, outputStream);

        writer.setInitialLeading(12);
        writer.setPageEvent(new PageSizer());
        document.open();

        PdfPTable table = new PdfPTable(4);

        // Add the header row
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("Form Name");
        table.addCell("Task Name");
        table.addCell("Status");
        table.addCell("Assigned To");

        table.setHeaderRows(1);

        // Add the task data

        table.getDefaultCell().setBackgroundColor(null);
        for (TaskFeature tf : t.features) {
            TaskProperties p = tf.properties;

            table.addCell(p.survey_name);
            table.addCell(p.name);
            table.addCell(p.status);
            table.addCell(p.assignee_name);

        }

        document.add(table);
        document.close();

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    }

}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser,
        String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape
        HttpServletResponse response) throws Exception {

    if (language != null) {
        language = language.replace("'", "''"); // Escape apostrophes
    } else {/*from  w  w w  . ja  va  2s .  co  m*/
        language = "none";
    }

    mExcludeEmpty = survey.exclude_empty;

    User user = null;

    ServerManager serverManager = new ServerManager();
    ServerData serverData = serverManager.getServer(sd, localisation);

    UserManager um = new UserManager(localisation);
    int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels

    Document document = null;
    PdfWriter writer = null;
    PdfReader reader = null;
    PdfStamper stamper = null;

    try {

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            //FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        defaultFontLink.setColor(BaseColor.BLUE);

        /*
         * Get the results and details of the user that submitted the survey
         */

        log.info("User Ident who submitted the survey: " + survey.instance.user);
        String userName = survey.instance.user;
        if (userName == null) {
            userName = remoteUser;
        }
        if (userName != null) {
            user = um.getByIdent(sd, userName);
        }

        // If a filename was not specified then get one from the survey data
        // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here
        // If the PDF is to be returned in an http response then the header is set now before writing to the output stream
        log.info("Filename passed to createPDF is: " + filename);
        if (filename == null) {
            filename = survey.getInstanceName() + ".pdf";
        } else {
            if (!filename.endsWith(".pdf")) {
                filename += ".pdf";
            }
        }

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            GeneralUtilityMethods.setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id);

        /*
         * Get dependencies between Display Items, for example if a question result should be added to another
         *  question's results
         */
        GlobalVariables gv = new GlobalVariables();
        if (!generateBlank) {
            for (int i = 0; i < survey.instance.results.size(); i++) {
                getDependencies(gv, survey.instance.results.get(i), survey, i);
            }
        }
        gv.mapbox_key = serverData.mapbox_default;
        int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser);

        languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language);
        if (templateFile.exists()) {

            log.info("PDF Template Exists");
            String templateName = templateFile.getAbsolutePath();

            reader = new PdfReader(templateName);
            stamper = new PdfStamper(reader, outputStream);

            for (int i = 0; i < survey.instance.results.size(); i++) {
                fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i,
                        serverRoot, stamper, oId);
            }
            if (user != null) {
                fillTemplateUserDetails(stamper.getAcroFields(), user, basePath);
            }
            stamper.setFormFlattening(true);

        } else {
            log.info("++++No template exists creating a pdf file programmatically");

            /*
             * Create a PDF without the stationary
             * If we need to add a letter head then create document in two passes, the second pass adds the letter head
             * Else just create the document directly in a single pass
             */
            Parser parser = getXMLParser();

            // Step 1 - Create the underlying document as a byte array
            if (landscape) {
                document = new Document(PageSize.A4.rotate());
            } else {
                document = new Document(PageSize.A4);
            }
            document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
            writer = PdfWriter.getInstance(document, outputStream);

            writer.setInitialLeading(12);

            writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null,
                    marginLeft, marginRight, marginTop_2, marginBottom_2));
            document.open();

            // If this form has data maintain a list of parent records to lookup ${values}
            ArrayList<ArrayList<Result>> parentRecords = null;
            if (!generateBlank) {
                parentRecords = new ArrayList<ArrayList<Result>>();
            }

            for (int i = 0; i < survey.instance.results.size(); i++) {
                processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                        generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId);
            }

            fillNonTemplateUserDetails(document, user, basePath);

            // Add appendix
            if (gv.hasAppendix) {
                document.newPage();
                document.add(new Paragraph("Appendix", defaultFontBold));

                for (int i = 0; i < survey.instance.results.size(); i++) {
                    processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                            generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId);
                }
            }

        }

    } finally {
        if (document != null)
            try {
                document.close();
            } catch (Exception e) {
            }
        ;
        if (writer != null)
            try {
                writer.close();
            } catch (Exception e) {
            }
        ;
        if (stamper != null)
            try {
                stamper.close();
            } catch (Exception e) {
            }
        ;
        if (reader != null)
            try {
                reader.close();
            } catch (Exception e) {
            }
        ;
    }

    return filename;

}

From source file:org.smap.sdal.managers.PDFTableManager.java

License:Open Source License

public void createPdf(Connection sd, OutputStream outputStream, ArrayList<ArrayList<KeyValue>> dArray,
        SurveyViewDefn mfc, ResourceBundle localisation, String tz, boolean landscape, String remoteUser,
        String basePath, String title, String project) {

    User user = null;//w ww.  ja  v a2s  .c o  m
    UserManager um = new UserManager(localisation);

    try {

        user = um.getByIdent(sd, remoteUser);

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        ArrayList<PdfColumn> cols = getPdfColumnList(mfc, dArray, localisation);
        ArrayList<String> tableHeader = new ArrayList<String>();
        for (PdfColumn col : cols) {
            tableHeader.add(col.displayName);
        }
        /*
         * Create a PDF without the stationary
         */
        PdfWriter writer = null;

        /*
         * If we need to add a letter head then create document in two passes, the second pass adds the letter head
         * Else just create the document directly in a single pass
         */
        Parser parser = getXMLParser();

        // Step 1 - Create the underlying document as a byte array
        Document document = null;
        if (landscape) {
            document = new Document(PageSize.A4.rotate());
        } else {
            document = new Document(PageSize.A4);
        }
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
        writer = PdfWriter.getInstance(document, outputStream);

        writer.setInitialLeading(12);
        writer.setPageEvent(new PdfPageSizer(title, project, user, basePath, tableHeader, marginLeft,
                marginRight, marginTop_2, marginBottom_2));

        document.open();
        document.add(new Chunk("")); // Ensure there is something in the page so at least a blank document will be created
        processResults(parser, document, dArray, cols, basePath);
        document.close();

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    }

}

From source file:pdf.PdfBuilder.java

/**
 * Creates an accessible PDF with images and text.
 * @param dest  the path to the resulting PDF
 * @throws IOException//w  w  w  .ja  va  2s.  c  om
 * @throws DocumentException
 */
public String createPdf(Invoice invoice) throws IOException, DocumentException {
    DEST = "C://temp/";
    SimpleDateFormat sdf = new SimpleDateFormat("MM");
    DEST += invoice.getCar().getId() + "month"
            + sdf.format(invoice.getSeriesOfLocationsOnRoad().get(0).getLocations().get(0).getDate()) + ".pdf";

    File file = new File(DEST);
    file.getParentFile().mkdirs();

    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
    writer.setPdfVersion(PdfWriter.VERSION_1_7);
    //TAGGED PDF
    //Make document tagged
    writer.setTagged();
    //===============
    //PDF/UA
    //Set document metadata
    writer.setViewerPreferences(PdfWriter.DisplayDocTitle);
    document.addLanguage("en-US");
    document.addTitle("Factuur voor auto " + invoice.getCar().getLicensePlate());
    writer.createXmpMetadata();
    //=====================
    document.open();

    Font font = FontFactory.getFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 20);

    double amountPaidForDistance = invoice.getTotalAmount();
    double amountPaidForCordons = 0;

    for (Cordon c : invoice.getCordonOccurrences()) {
        amountPaidForDistance -= c.getAmount();
        amountPaidForCordons += c.getAmount();
    }

    Paragraph p = new Paragraph("\n", font);
    p.add(new Chunk("Aantal gereden kilometers:"));
    p.add(new Chunk("\n"));
    p.add(new Chunk(String.valueOf(invoice.getTotalDistance()) + " kilometer"));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Met een gemiddeld tarief van " + (amountPaidForDistance / invoice.getTotalDistance() * 100)
            + " eurocent per kilometer"));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Bedrag dat betaald dient te worden over de kilometers: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(amountPaidForDistance + " euro"));
    document.add(p);

    p = new Paragraph("\n\n", font);
    p.add(new Chunk(invoice.cordonOccurrencesString()));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Bedrag dat betaald dient te worden over de cordons: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(amountPaidForCordons + " euro"));
    document.add(p);

    p = new Paragraph("\n\n", font);
    p.add(new Chunk("Totaal bedrag dat betaald dient te worden: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(String.valueOf(invoice.getTotalAmount()) + " euro"));
    document.add(p);
    document.close();

    return DEST;
}

From source file:pdf.PDFDesign.java

public PDFDesign(String s, String c, String sn, Map<String, String> fontMap) {
    size = s;//from  w ww  . j av a 2 s .  c  o  m
    titleLineFixedHeight = 15.0f;
    priceFontInc = 0;
    textFontInc = 0;
    styleName = sn;
    fontPaths = new FontPaths(fontMap);
    nColumns = 6;
    switch (c) {
    case "black":
        color = BaseColor.BLACK;
        break;
    case "gray":
        color = BaseColor.DARK_GRAY;
        break;
    case "red":
        color = BaseColor.RED.darker();
        break;
    case "green":
        color = BaseColor.GREEN.darker().darker().darker();
        break;
    case "blue":
        color = BaseColor.BLUE.darker().darker().darker();
        break;
    default:
        this.color = BaseColor.BLACK;
    }
    switch (size) {
    case "3x5":
        cellHeight = 83.8f;
        break;
    case "3.5x5":
        cellHeight = 97.8f;
        break;
    case "3.5x6":
        priceFontInc = 8;
        cellHeight = 97.8f;
        nColumns = 5;
        break;
    case "3.5x7":
        cellHeight = 97.8f;
        nColumns = 4;
        break;
    case "4x6":
        titleLineFixedHeight = 26.0f;
        priceFontInc = 8;
        cellHeight = 117.0f;
        nColumns = 5;
        break;
    case "4x7":
        titleLineFixedHeight = 26.0f;
        priceFontInc = 8;
        cellHeight = 117.0f;
        nColumns = 4;
        break;
    case "5x6":
        titleLineFixedHeight = 30.0f;
        priceFontInc = 13;
        textFontInc = 2;
        cellHeight = 145.0f;
        nColumns = 5;
        break;
    case "5x7":
        titleLineFixedHeight = 30.0f;
        priceFontInc = 18;
        textFontInc = 3;
        cellHeight = 145.0f;
        nColumns = 4;
        break;
    case "6x7":
        titleLineFixedHeight = 34.0f;
        priceFontInc = 26;
        textFontInc = 5;
        cellHeight = 175.0f;
        nColumns = 4;
        break;
    }
    try {
        int normal = Font.NORMAL;
        int bold = Font.BOLD;

        droidsans = BaseFont.createFont(fontPaths.getPath("droidsans"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        BaseFont impact = BaseFont.createFont(fontPaths.getPath("impact"), BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);

        switch (styleName) {
        case "style1":
            BaseFont courier = BaseFont.createFont(fontPaths.getPath("courier"), BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            initValues(42f, new Font(courier, 12 + textFontInc, normal, color),
                    new Font(courier, 9 + textFontInc, normal, color),
                    new Font(impact, 43 + priceFontInc + textFontInc, normal, color),
                    new Font(courier, 20 + textFontInc, normal, color),
                    new Font(courier, 8 + textFontInc, normal, color));
            break;
        case "style2":
            BaseFont digital7 = BaseFont.createFont(fontPaths.getPath("digital7"), BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            initValues(42f, new Font(droidsans, 10 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color),
                    new Font(digital7, 55 + priceFontInc + textFontInc, normal, color),
                    new Font(digital7, 30, normal, color), new Font(droidsans, 7 + textFontInc, normal, color));
            break;
        case "style3":
            BaseFont modern = BaseFont.createFont(fontPaths.getPath("modern"), BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            initValues(40f, new Font(droidsans, 10 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color),
                    new Font(modern, 55 + priceFontInc + textFontInc, normal, color),
                    new Font(modern, 30, normal, color), new Font(droidsans, 7 + textFontInc, normal, color));
            break;
        case "style4":
            BaseFont gothic = BaseFont.createFont(fontPaths.getPath("gothic"), BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            initValues(40f, new Font(droidsans, 10 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color),
                    new Font(gothic, 48 + priceFontInc + textFontInc, bold, color),
                    new Font(gothic, 30, bold, color), new Font(droidsans, 7 + textFontInc, normal, color));
            break;
        case "style5":
            BaseFont bookman = BaseFont.createFont(fontPaths.getPath("bookman"), BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            initValues(35f, new Font(droidsans, 10 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color),
                    new Font(bookman, 45 + priceFontInc + textFontInc, bold, color),
                    new Font(bookman, 25, normal, color), new Font(droidsans, 7 + textFontInc, normal, color));
            break;

        case "style6":
            initValues(45f, new Font(droidsans, 10 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color),
                    new Font(impact, 45 + priceFontInc + textFontInc, normal, color),
                    new Font(droidsans, 20 + textFontInc, normal, color),
                    new Font(droidsans, 7 + textFontInc, normal, color));
            break;

        default:
            System.out.println("[*] Unknown Style");
            break;
        }

    } catch (DocumentException | IOException ex) {
        System.out.println("[E] " + ex.getMessage());
    }
}

From source file:pdfMaker.MakePdfFile.java

public void createPdf(String mainTitle, String subTitle, String url, String userName,
        //String scanType,
        String comment,/* www  .ja  v a2  s.co  m*/
        //String thisPassCode,
        String passCodeA, String passCodeB, String fileDir, Boolean noBarCodePrint)
        throws IOException, DocumentException, RuntimeException {
    Document document = null;
    try {
        // step 1
        document = new Document(PageSize.A4, 60, 50, 50, 35);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileDir));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        /*
         Properties props = new Properties();
         String jarPath = System.getProperty("java.class.path");
         String dirPath = jarPath.substring(0, jarPath.lastIndexOf(File.separator)+1);
         FontFactory.registerDirectory("/res");
         FontFactory.register("ipag.ttf");
         Font ipaGothic = FontFactory.getFont("ipag", BaseFont.IDENTITY_H, 
         BaseFont.EMBEDDED, 10); //10 is the size
                
         InputStream is = getClass().getResourceAsStream("/res/ipag.ttf");
         */

        Properties props = new Properties();
        String jarPath = System.getProperty("java.class.path");
        String dirPath = jarPath.substring(0, jarPath.lastIndexOf(File.separator) + 1);
        System.out.println(jarPath);
        System.out.println(dirPath);
        System.out.println(System.getProperty("user.dir"));

        Font ipaGothic = new Font(BaseFont.createFont(System.getProperty("user.dir") + "\\res\\ipag.ttf",
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 11);

        //?(2)
        PdfPTable pdfPTable = new PdfPTable(2);

        pdfPTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfPTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfPTable.getDefaultCell().setFixedHeight(150);

        pdfPTable.setWidthPercentage(100f);

        int pdfPTableWidth[] = { 10, 90 };
        pdfPTable.setWidths(pdfPTableWidth);

        PdfPCell cell_1_1 = new PdfPCell(new Paragraph("??", ipaGothic));
        cell_1_1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell_1_1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell_1_1.setFixedHeight(50);
        PdfPCell cell_1_2 = new PdfPCell(new Paragraph(mainTitle, ipaGothic));
        cell_1_2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell_1_2.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell_2_1 = new PdfPCell(new Paragraph("", ipaGothic));
        cell_2_1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell_2_1.setHorizontalAlignment(Element.ALIGN_CENTER);
        PdfPCell cell_2_2 = new PdfPCell(new Paragraph(subTitle, ipaGothic));
        cell_2_2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell_2_2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell_2_2.setFixedHeight(50);
        pdfPTable.addCell(cell_1_1);
        pdfPTable.addCell(cell_1_2);
        pdfPTable.addCell(cell_2_1);
        pdfPTable.addCell(cell_2_2);

        PdfPCell cellUrlKey = new PdfPCell(new Paragraph("?", ipaGothic));
        cellUrlKey.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellUrlKey.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellUrlKey.setRowspan(2);
        pdfPTable.addCell(cellUrlKey);

        PdfPCell cellUrlValue = new PdfPCell(new Paragraph(url, ipaGothic));
        cellUrlValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellUrlValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellUrlValue.setFixedHeight(50);
        pdfPTable.addCell(cellUrlValue);

        /*  */
        //cellUrlValue.getImage();
        writer.getDirectContent().addImage(cellUrlValue.getImage(), 100, 100, 100, 100, 100, 100);

        if (url.length() != 0 && !noBarCodePrint) {
            /* ?
             BarcodeQRCode qr = new BarcodeQRCode(url, 50, 50, null);
             PdfPCell cellUrlValueQr = new PdfPCell(qr.getImage());
             cellUrlValueQr.setVerticalAlignment(Element.ALIGN_MIDDLE);
             cellUrlValueQr.setHorizontalAlignment(Element.ALIGN_CENTER);
             cellUrlValueQr.setFixedHeight(80);
             pdfPTable.addCell(cellUrlValueQr);
             */
            Image image = ZxingUti.getQRCode(url); //  SHIFT_JIS
            com.itextpdf.text.Image iTextImage = com.itextpdf.text.Image.getInstance(image, null);
            PdfPCell cell = new PdfPCell(iTextImage);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(100);
            pdfPTable.addCell(cell); //  SIFT_JIS
        } else {
            PdfPCell cellUrlValueQr = new PdfPCell(new Paragraph("", ipaGothic));
            cellUrlValueQr.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellUrlValueQr.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellUrlValueQr.setFixedHeight(80);
            pdfPTable.addCell(cellUrlValueQr);
        }

        PdfPCell cellUserNameKey = new PdfPCell(new Paragraph("", ipaGothic));
        cellUserNameKey.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellUserNameKey.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellUserNameKey.setRowspan(2);
        pdfPTable.addCell(cellUserNameKey);

        PdfPCell cellUserNameValue = new PdfPCell(new Paragraph(userName, ipaGothic));
        cellUserNameValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellUserNameValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellUserNameValue.setFixedHeight(30);
        pdfPTable.addCell(cellUserNameValue);

        if (userName.length() != 0 && !noBarCodePrint) {
            Barcode128 code128 = new Barcode128();
            code128.setCode(userName);
            code128.setFont(ipaGothic.getBaseFont());
            code128.setBarHeight(40f);
            PdfPCell cellUserNameValueBc = new PdfPCell(code128.createImageWithBarcode(cb, null, null));
            cellUserNameValueBc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellUserNameValueBc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellUserNameValueBc.setFixedHeight(80);
            pdfPTable.addCell(cellUserNameValueBc);
        } else {
            PdfPCell cellUserNameValueBc = new PdfPCell(new Paragraph("---", ipaGothic));
            cellUserNameValueBc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellUserNameValueBc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellUserNameValueBc.setFixedHeight(80);
            pdfPTable.addCell(cellUserNameValueBc);
        }

        PdfPCell cellPassCodeKey = new PdfPCell(new Paragraph("?", ipaGothic));
        cellPassCodeKey.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellPassCodeKey.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellPassCodeKey.setRowspan(3);
        pdfPTable.addCell(cellPassCodeKey);

        PdfPCell cellPassCodeValue = new PdfPCell(new Paragraph(passCodeA + passCodeB, ipaGothic));
        cellPassCodeValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellPassCodeValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellPassCodeValue.setFixedHeight(30);
        pdfPTable.addCell(cellPassCodeValue);

        if (passCodeA.length() != 0 && !noBarCodePrint) {
            Barcode128 code128 = new Barcode128();
            code128.setCode(passCodeA);
            code128.setFont(ipaGothic.getBaseFont());
            code128.setBarHeight(40f);
            PdfPCell cellPassCodeA_Bc = new PdfPCell(code128.createImageWithBarcode(cb, null, null));
            cellPassCodeA_Bc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellPassCodeA_Bc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPassCodeA_Bc.setFixedHeight(80);
            pdfPTable.addCell(cellPassCodeA_Bc);
        } else {
            PdfPCell cellPassCodeA_Bc = new PdfPCell(new Paragraph("---", ipaGothic));
            cellPassCodeA_Bc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellPassCodeA_Bc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPassCodeA_Bc.setFixedHeight(80);
            pdfPTable.addCell(cellPassCodeA_Bc);
        }

        if (passCodeB.length() != 0 && !noBarCodePrint) {
            Barcode128 code128 = new Barcode128();
            code128.setCode(passCodeB);
            code128.setFont(ipaGothic.getBaseFont());
            code128.setBarHeight(40f);
            PdfPCell cellPassCodeB_Bc = new PdfPCell(code128.createImageWithBarcode(cb, null, null));
            cellPassCodeB_Bc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellPassCodeB_Bc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPassCodeB_Bc.setFixedHeight(80);
            pdfPTable.addCell(cellPassCodeB_Bc);
        } else {
            PdfPCell cellPassCodeB_Bc = new PdfPCell(new Paragraph("---", ipaGothic));
            cellPassCodeB_Bc.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellPassCodeB_Bc.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPassCodeB_Bc.setFixedHeight(80);
            pdfPTable.addCell(cellPassCodeB_Bc);
        }

        PdfPCell cellCommentKey = new PdfPCell(new Paragraph("?", ipaGothic));
        cellCommentKey.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellCommentKey.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfPTable.addCell(cellCommentKey);

        PdfPCell cellCommentValue = new PdfPCell(new Paragraph(comment, ipaGothic));
        cellCommentValue.setVerticalAlignment(Element.ALIGN_TOP);
        cellCommentValue.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellCommentValue.setFixedHeight(150);
        pdfPTable.addCell(cellCommentValue);

        PdfPCell cellIssueKey = new PdfPCell(new Paragraph("", ipaGothic));
        cellIssueKey.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellIssueKey.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfPTable.addCell(cellIssueKey);

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        String strDate = sdf.format(cal.getTime());
        PdfPCell cellIssueValue = new PdfPCell(new Paragraph(strDate, ipaGothic));
        cellIssueValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cellIssueValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellIssueValue.setFixedHeight(20);
        pdfPTable.addCell(cellIssueValue);

        //??
        document.add(pdfPTable);
        /*
                
         // CODE 128
         document.add(new Paragraph("?? : " + mainTitle, ipaGothic));
         document.add(new Paragraph(" : " + subTitle, ipaGothic));
         document.add(new Paragraph("-------------------------------------------------------"));
         document.add(new Paragraph(" " + strDate));
         document.add(new Paragraph("-------------------------------------------------------"));
                
                
         BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.WINANSI, BaseFont.EMBEDDED);
         Font font = new Font(bf, 12);
         document.add(new Paragraph("", ipaGothic));
         document.add(new Paragraph(url, ipaGothic));
         code128.setCode(url);
         code128.setFont(bf);
         code128.setX(1);
         //document.add(code128.createImageWithBarcode(cb, null, null));
                
         document.add(new Paragraph("USER", ipaGothic));
         if (userName.length() != 0) {
         document.add(new Paragraph(userName, ipaGothic));
         code128.setCode(userName);
         code128.setFont(bf);
         code128.setBarHeight(40f);
         document.add(code128.createImageWithBarcode(cb, null, null));
         }
                
         document.add(new Paragraph("CODE", ipaGothic));
         if (passCode.length() != 0) {
         document.add(new Paragraph(passCode, ipaGothic));
         code128.setCode(passCode);
         code128.setFont(bf);
         document.add(code128.createImageWithBarcode(cb, null, null));
         }
                
         document.add(new Paragraph("?", ipaGothic));
         document.add(new Paragraph(comment, ipaGothic));
         */
        // step 5
        document.close();
    } catch (RuntimeException ex) {
        document.close();
        throw ex;

    }
}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args/*w ww .  ja  v  a2  s.  c o m*/
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}