Example usage for com.itextpdf.text.pdf PdfWriter getDirectContent

List of usage examples for com.itextpdf.text.pdf PdfWriter getDirectContent

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter getDirectContent.

Prototype


public PdfContentByte getDirectContent() 

Source Link

Document

Use this method to get the direct content for this document.

Usage

From source file:org.ujmp.itext.ExportPDF.java

License:Open Source License

public static final void save(File file, Component c, int width, int height) {
    if (file == null) {
        logger.log(Level.WARNING, "no file selected");
        return;/*from   w  ww  .  ja  v a  2 s  .  c  om*/
    }
    if (c == null) {
        logger.log(Level.WARNING, "no component provided");
        return;
    }
    try {
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath()));
        document.addAuthor("UJMP v" + UJMP.UJMPVERSION);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper());
        if (c instanceof CanRenderGraph) {
            ((CanRenderGraph) c).renderGraph(g2);
        } else {
            c.paint(g2);
        }
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        writer.close();
    } catch (Exception e) {
        logger.log(Level.WARNING, "could not save PDF file", e);
    }
}

From source file:org.unesco.jisis.printsort.BarCodeGenerator.java

public void generateBarCode() {
    /** Step 1: Create a Document*/
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    try {/*  www. j a  v a 2  s. co  m*/

        /** Step 2: Create PDF Writer*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("sanjaalDotCom_BarCode1.pdf"));

        /** Step 3: Open the document so that we can write over it.*/
        document.open();

        /** Step 4: We have to create a set of contents.*/
        contentByte = writer.getDirectContent();

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.getDefaultCell().setFixedHeight(70);

        String myText = "www.sanjaal.com"; // Text to encode

        table.addCell("CODE 39");
        table.addCell(new Phrase(new Chunk(createBarCode39(myText.toUpperCase()), 0, 0)));

        table.addCell("CODE 39 EXTENDED");
        table.addCell(new Phrase(new Chunk(createBarcode39Extended(myText), 0, 0)));

        table.addCell("CODE 128");
        table.addCell(new Phrase(new Chunk(createBarcode128(myText), 0, 0)));

        table.addCell("CODE INTERLEAVED");
        String myTextNum = "12345";
        table.addCell(new Phrase(new Chunk(createBarcodeInter25(myTextNum), 0, 0)));

        table.addCell("CODE POSTNET");
        table.addCell(new Phrase(new Chunk(createBarcodePostnet(myTextNum), 0, 0)));

        table.addCell("CODE PLANET");
        table.addCell(new Phrase(new Chunk(createBarcodePostnetPlanet(myTextNum), 0, 0)));

        String myTextEAN13 = "1234567890123";
        table.addCell("CODE EAN");
        table.addCell(new Phrase(new Chunk(createBarcodeEAN(myTextEAN13), 0, 0)));

        table.addCell("CODE EAN\nWITH\nSUPPLEMENTAL 5");
        table.addCell(new Phrase(new Chunk(createBARCodeEANSUPP(myTextEAN13, "12345"), 0, 0)));

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }

    // step 5: we close the document
    document.close();
}

From source file:pdf.FooterHeader.java

License:Open Source License

public FooterHeader(String Titel, PdfWriter writer) {
    header = new Phrase(Titel);
    total = writer.getDirectContent().createTemplate(30, 16);
}

From source file:pdf.FooterHeader.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    PdfPTable table = new PdfPTable(3);
    try {//from   w  ww .ja v a  2 s .  c  om
        if (document.getPageNumber() > 1) {
            table.setWidths(new int[] { 24, 24, 2 });
            table.setTotalWidth(527);
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(20);
            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            table.addCell(header);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(String.format("Seite %d von", writer.getPageNumber()));
            PdfPCell cell = new PdfPCell(Image.getInstance(total));
            cell.setBorder(Rectangle.BOTTOM);
            table.addCell(cell);
            table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
        }
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }

    PdfContentByte cb = writer.getDirectContent();
    if (document.getPageNumber() > 1) {
        footer = new Phrase(document.getPageNumber() - 2);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer,
                (document.right() - document.left() - 30) / 2 + document.leftMargin(), document.bottom() + 10,
                0);
    }

}

From source file:pdf.PdfCreator.java

public String createPdf(String path, String ingredients, String recipeTitle, String recipeDescription)
        throws DocumentException, IOException {
    path += "shoppingList.pdf";
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();/*from   ww w . j  av  a  2s.  c o m*/
    String[] ings = ingredients.split(";");

    PdfContentByte cb = writer.getDirectContent();
    BaseFont bf = BaseFont.createFont();
    cb.beginText();
    Paragraph p = new Paragraph("Ingredients you'll need to buy:",
            new Font(FontFamily.HELVETICA, 20, Font.BOLD, new BaseColor(38, 165, 154)));
    p.add(Chunk.NEWLINE);
    document.add(p);

    cb.moveText(36, 750);
    cb.setFontAndSize(bf, 15);
    cb.endText();

    p = new Paragraph();
    for (String str : ings) {
        p.add(" ");
        p.add(str);
        p.add(Chunk.NEWLINE);
    }
    p.add(Chunk.NEWLINE);
    p.add(Chunk.NEWLINE);
    document.add(p);

    p = new Paragraph(recipeTitle, new Font(FontFamily.HELVETICA, 20, Font.BOLD, new BaseColor(38, 165, 154)));
    p.add(Chunk.NEWLINE);
    document.add(p);
    p = new Paragraph(recipeDescription, new Font(bf, 12));
    p.add(Chunk.NEWLINE);
    document.add(p);

    document.close();
    return path;
}

From source file:PDF.Reportes.java

public void reportesPDF(HttpServletResponse response, int tr, ServletContext d, String usuario, String contra,
        String horario, int opc) {
    String reporteT = "";
    try {//from w  w w  .j  ava  2s  . c o m

        Document reporte = new Document();
        Calendar cal = Calendar.getInstance();

        Paragraph intro = new Paragraph();
        intro.setAlignment(Element.ALIGN_CENTER);

        String linea = "/Imagenes/rallita.png";
        String absolute_url_linea = d.getRealPath(linea);

        Image linea_div = Image.getInstance(absolute_url_linea);

        Paragraph vacio = new Paragraph("  ", FontFactory.getFont("arial", 10));
        vacio.setAlignment(Element.ALIGN_CENTER);

        if (tr == 0) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(vacio);
            reporte.add(vacio);
            ArrayList<JFreeChart> graf = grafica(usuario, contra);
            if (graf == null) {

                intro = new Paragraph(
                        "Lo sentimos, por el momento an no existe informacin para este reporte.",
                        FontFactory.getFont("arial", 18));

                reporte.add(intro);
            } else {
                for (int i = 0; i < graf.size(); i++) {
                    BufferedImage bufferedImage = graf.get(i).createBufferedImage(500, 300);
                    Image chart = Image.getInstance(writer, bufferedImage, 1.0f);
                    reporte.add(vacio);
                    reporte.add(chart);
                }
            }
            reporteT = "Estadsticas de registros.";
        }
        if (tr == 1) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Sin alta en CENEVAL " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);
            reporte.add(noaltaCen(usuario, contra));
            reporteT = "Sin alta en CENEVAL.";
        }
        if (tr == 2) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Estatus Prefichas " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);

            reporte.add(statusfichas(usuario, contra));
            reporteT = "Estatus prefichas";
        }
        if (tr == 3) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Pre proceso concluido " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);
            reporte.add(procesoCon(usuario, contra));
            reporteT = "Pre proceso concluido";
        }
        if (tr == 4) {

            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            ArrayList<PdfPTable> tables = firmasAspAula(usuario, contra, horario, opc);
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent2 event = new HeaderFooterPageEvent2("ficha-pdf.png");
            writer.setPageEvent(event);
            reporte.open();

            if (tables.size() != 1) {
                PdfPTable tableH = tables.get(tables.size() - 1);
                tableH.writeSelectedRows(0, -1, 10, 720, writer.getDirectContent());
            } else {
                reporte.add(tables.get(0));
            }
            reporte.add(vacio);

            reporte.add(vacio);
            reporte.add(vacio);
            for (int i = 0; i < tables.size(); i++) {

                if (i + 1 != tables.size()) {

                    reporte.add(tables.get(i));
                    if (i + 2 != tables.size()) {
                        reporte.newPage();
                    }
                }

            }

            reporteT = "Firmas Aspirantes_" + horario;

        }
        if (tr == 5) {

            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            ArrayList<PdfPTable> tables = tablaAspAula(usuario, contra, horario, opc);
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent2 event = new HeaderFooterPageEvent2("ficha-pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            if (tables.size() != 1) {
                PdfPTable tableH = tables.get(tables.size() - 1);
                tableH.writeSelectedRows(0, -1, 10, 720, writer.getDirectContent());
            } else {
                reporte.add(tables.get(0));
            }

            reporte.add(vacio);

            reporte.add(vacio);
            reporte.add(vacio);
            for (int i = 0; i < tables.size(); i++) {

                if (i + 1 != tables.size()) {

                    reporte.add(tables.get(i));
                    if (i + 2 != tables.size()) {
                        reporte.newPage();
                    }
                }

            }

            reporteT = "Aspirantes por aula horario_" + horario;

        }

        reporte.addTitle("Reportes_" + reporteT);
        reporte.addSubject("Instituto Tecnolgico de Toluca");
        reporte.addKeywords("Instituto Tecnolgico de Toluca");
        reporte.addAuthor("Coordinacion de desarrollo de sistemas");
        reporte.addCreator("Centro de Cmputo ITT");

        //Asignamos el manejador de eventos al escritor.
        reporte.close();

    } catch (DocumentException | IOException ex) {
        Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:pdf.SplitPDF.java

public static void splitPDF(InputStream inputStream, OutputStream outputStream, int fromPage, int toPage) {
    Document document = new Document();
    try {/* ww  w .  ja v  a 2  s .  c  om*/
        PdfReader inputPDF = new PdfReader(inputStream);

        int totalPages = inputPDF.getNumberOfPages();

        //make fromPage equals to toPage if it is greater
        if (fromPage > toPage) {
            fromPage = toPage;
        }
        if (toPage > totalPages) {
            toPage = totalPages;
        }

        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;

        while (fromPage <= toPage) {
            document.newPage();
            page = writer.getImportedPage(inputPDF, fromPage);
            cb.addTemplate(page, 0, 0);
            fromPage++;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:pdfMaker.MakePdfFile.java

MakePdfFile(String text1, String text2, String text3) throws IOException, DocumentException, RuntimeException {

    // /* ww  w.ja  v  a 2 s . c  om*/
    url = text1;

    Document document = null;
    String fileDir = "TEST_MAT.pdf";
    // step 1
    document = new Document(PageSize.A4, 20, 20, 20, 20);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileDir));

    // step 3
    document.open();
    // step 4
    PdfContentByte cb = writer.getDirectContent();

    Image image = ZxingUti.getQRCode(url); //  SHIFT_JIS
    com.itextpdf.text.Image iTextImage = com.itextpdf.text.Image.getInstance(image, null);

    // http://d.hatena.ne.jp/MoonMtLab/20130920/1379626380
    //Image??
    com.itextpdf.text.Image img = iTextImage;

    //??()
    img.setAbsolutePosition(document.getPageSize().getWidth() - 30, document.getPageSize().getHeight() - 30);
    System.out.println(document.getPageSize().getWidth());
    System.out.println(document.getPageSize().getHeight());
    //?
    img.scaleAbsolute(30, 30);

    //PdfContentByte??
    PdfContentByte pdfContentByte = writer.getDirectContent();

    //???
    pdfContentByte.addImage(img);

    /* 
     writer.setEncryption("Hello".getBytes(), "World".getBytes(),
     PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
     // 
     */
    document.close();

}

From source file:pdfMaker.MakePdfFile.java

public void createPdf(String mainTitle, String subTitle, String url, String userName,
        //String scanType,
        String comment,/*from   w w  w.j  a  va2 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  w  w.j  av a2  s.  c  om*/
 */
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();
    }
}