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:printInv.GenerateInvoice.java

private void createPDF(String pdfFilename) {

    Document doc = new Document();
    PdfWriter docWriter = null;
    initializeFonts();// ww w  .  j a  va  2 s .c o m

    try {
        //   String path = "docs/" + pdfFilename;
        String path = pdfFilename;
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.addAuthor("SmartWMS");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("SmartWMS");
        doc.addTitle("Invoice");
        doc.setPageSize(PageSize.LETTER);

        doc.open();
        PdfContentByte cb = docWriter.getDirectContent();

        boolean beginPage = true;
        int y = 0;
        System.out.println("n ===========" + n);
        for (int i = 0; i < n; i++) {
            if (beginPage) {
                beginPage = false;
                generateLayout(doc, cb);
                generateHeader(doc, cb);
                y = 615;
            }
            generateDetail(doc, cb, i, y);
            y = y - 15;
            if (y < 50) {
                printPageNumber(cb);
                doc.newPage();
                beginPage = true;
            }
        }
        printPageNumber(cb);
        cb.beginText();
        cb.setFontAndSize(bfBold, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Grand Total : " + total, 570, 35, 0);
        cb.endText();

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }
}

From source file:psManage.StructSheet.java

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

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

        //?(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));
        Chunk chunk = new Chunk(url, ipaGothic); // ??????????????
        System.out.println("??" + chunk.getWidthPoint());
        cellUrlValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
        if (chunk.getWidthPoint() > 410) { // ??????????
            cellUrlValue.setHorizontalAlignment(Element.ALIGN_LEFT);
        } else { // ?????????
            cellUrlValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        }

        cellUrlValue.setFixedHeight(50);
        pdfPTable.addCell(cellUrlValue);

        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, ipaGothic14));
        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, ipaGothic14));
        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:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java

License:Open Source License

/** Export PDF to a file.
 *  This uses the iText library at http://itextpdf.com/.
 *
 *  <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true
 *  then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser
 *  is used.</p>//from ww w.j  a va2 s .c o  m
 */
private void _exportPDF() {
    Dimension size = _frame.getContentSize();
    Rectangle pageSize = null;
    try {
        pageSize = new Rectangle(size.width, size.height);
    } catch (Throwable ex) {
        // This exception will occur if the iText library is not installed.
        MessageHandler.error("iText library is not installed. See http://itextpdf.com/."
                + "  You must have iText.jar in your classpath.  Sometimes, "
                + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex);
        return;
    }
    Document document = new Document(pageSize);
    JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix();
    Color background = null;
    PtFileChooser ptFileChooser = null;
    try {
        background = jFileChooserBugFix.saveBackground();

        ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.",
                JFileChooser.SAVE_DIALOG);

        LinkedList extensions = new LinkedList();
        extensions.add("pdf");
        ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions));

        BasicGraphFrame basicGraphFrame = null;
        if (_frame instanceof BasicGraphFrame) {
            basicGraphFrame = (BasicGraphFrame) _frame;
            ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory());
            ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf"));
        }
        int returnVal = ptFileChooser.showDialog(_frame, "Export PDF");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (basicGraphFrame != null) {
                basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory());
            }
            File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile();

            if (pdfFile.getName().indexOf(".") == -1) {
                // If the user has not given the file an extension, add it
                pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf");
            }

            // The Mac OS X FileDialog will ask if we want to save before this point.
            if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) {
                if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) {
                    return;
                }
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // To ensure Latex compatibility, use earlier PDF version.
            writer.setPdfVersion(PdfWriter.VERSION_1_3);
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();

            PdfTemplate template = contentByte.createTemplate(size.width, size.height);
            Graphics2D graphics = template.createGraphics(size.width, size.height);
            template.setWidth(size.width);
            template.setHeight(size.height);

            Paper paper = new Paper();
            paper.setSize(size.width, size.height);
            paper.setImageableArea(0.0, 0.0, size.width, size.height);
            PageFormat format = new PageFormat();
            format.setPaper(paper);
            ((Printable) _frame).print(graphics, format, 0);
            graphics.dispose();
            contentByte.addTemplate(template, 0, 0);

            // Open the PDF file.
            // FIXME: _read is protected in BasicGraphFrame
            //_read(pdfFile.toURI().toURL());
            // Open the image pdfFile.
            if (basicGraphFrame == null) {
                MessageHandler.message("PDF file exported to " + pdfFile.getName());
                /* Remove the following. The extra click is annoying...
                } else {
                if (MessageHandler.yesNoQuestion("Open \""
                        + pdfFile.getCanonicalPath() + "\" in a browser?")) {
                    Configuration configuration = basicGraphFrame
                            .getConfiguration();
                    try {
                        URL imageURL = new URL(pdfFile.toURI().toURL()
                                .toString()
                                + "#in_browser");
                        configuration.openModel(imageURL, imageURL,
                                imageURL.toExternalForm(),
                                BrowserEffigy.staticFactory);
                    } catch (Throwable throwable) {
                        MessageHandler.error(
                                "Failed to open \"" + pdfFile.getName()
                                        + "\".", throwable);
                    }
                }
                 */
            }
        }
    } catch (Exception e) {
        MessageHandler.error("Export to PDF failed", e);
    } finally {
        try {
            document.close();
        } finally {
            jFileChooserBugFix.restoreBackground(background);
        }
    }
}

From source file:py.com.palermo.imprimeetiquetas.web.ProductoController.java

public String createPdf() throws IOException, DocumentException {

    if (hayParaImprimir()) {

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        response.setContentType("application/x-pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"etiquetas.pdf\"");

        // step 1
        Document document = new Document(new Rectangle(86, 35));
        // step 2

        document.setMargins(0f, 0f, 0f, 0f);

        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        // step 3
        document.open();// www .jav  a  2 s.c  o m

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

        for (ProductoCantidad p : productos) {
            if (p.getCantidad() > 0) {

                BarcodeEAN codeEAN = new BarcodeEAN();
                codeEAN.setCode(p.getCodigo());
                codeEAN.setCodeType(Barcode.EAN13);
                codeEAN.setBarHeight(10f);
                codeEAN.setX(0.7f);
                codeEAN.setSize(4f);

                NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("es", "py"));
                Font fontbold = FontFactory.getFont("Times-Roman", 5, Font.NORMAL);
                Chunk productTitle = new Chunk(p.getNombre() + "," + " " + nf.format(p.getPrecio()), fontbold);

                // EAN 13
                Paragraph pTitile = new Paragraph(productTitle);
                pTitile.setAlignment(Element.ALIGN_CENTER);
                pTitile.setLeading(0, 1);

                PdfPTable table = new PdfPTable(1);
                table.setPaddingTop(0f);

                table.setWidthPercentage(96);
                PdfPCell cell = new PdfPCell();
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setBorder(Rectangle.NO_BORDER);
                cell.addElement(codeEAN.createImageWithBarcode(cb, null, BaseColor.BLACK));

                table.addCell(cell);

                PdfPCell cell2 = new PdfPCell();
                cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell2.setBorder(Rectangle.NO_BORDER);
                cell2.addElement(pTitile);

                table.addCell(cell2);

                for (int i = 0; i < p.getCantidad(); i++) {
                    document.add(table);
                    document.newPage();
                }
            }
        }

        // step 5
        document.close();

        response.getOutputStream().flush();
        response.getOutputStream().close();
        FacesContext.getCurrentInstance().responseComplete();
    } else {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "No hay nada que imprimir", ""));
    }
    return null;
}

From source file:registrosql.Registrar.java

public void PrintFrameToPDF(File file) {
    try {/*  www.ja v a  2 s .c  om*/
        Document d = new Document();
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(file));
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate template = cb.createTemplate(PageSize.LETTER.getWidth(), PageSize.LETTER.getHeight());
        cb.addTemplate(template, 0, 0);
        Graphics2D g2d = template.createGraphics(PageSize.LETTER.getWidth(), PageSize.LETTER.getHeight());
        g2d.scale(0.4, 0.4);
        for (int i = 0; i < this.getContentPane().getComponents().length; i++) {
            Component c = this.getContentPane().getComponent(i);
            if (c instanceof JLabel || c instanceof JScrollPane) {
                g2d.translate(c.getBounds().x, c.getBounds().y);
                if (c instanceof JScrollPane) {
                    c.setBounds(0, 0, (int) PageSize.LETTER.getWidth() * 2,
                            (int) PageSize.LETTER.getHeight() * 2);
                }
                c.paintAll(g2d);
                c.addNotify();
            }
        }
        g2d.dispose();
        d.close();
    } catch (Exception e) {
        System.out.println("ERROR: " + e.toString());
    }
}

From source file:Report.ItextReport.java

public static void absText(PdfWriter writer, String text, int x, int y) {
    try {/*from  www .  j a  va  2  s .  c om*/
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.saveState();
        cb.beginText();
        cb.moveText(x, y);
        cb.setFontAndSize(bf, 12);
        cb.showText(text);
        cb.endText();
        cb.restoreState();
    } catch (DocumentException | IOException e) {
        e.getMessage();
    }
}

From source file:ro.ldir.chartpackage.GarbagePackageBuilder.java

License:Open Source License

public void writePDF(OutputStream out)
        throws DocumentException, MalformedURLException, XPathExpressionException, IOException {
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, "Cp1250", BaseFont.NOT_EMBEDDED);
    final Font hfFont = new Font(bf, 8, Font.NORMAL, BaseColor.GRAY);

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    writer.setPageEvent(new PdfPageEventHelper() {
        private int page = 0;

        @Override/*  w w  w  .  j  av  a 2s  . co  m*/
        public void onEndPage(PdfWriter writer, Document arg1) {
            page++;
            Rectangle rect = writer.getBoxSize("art");
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("Pachet mormane - \u00a9 Let's Do It, Romania!", hfFont),
                    (rect.getLeft() + rect.getRight()) / 2, rect.getTop() + 18, 0);
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("- " + page + " -", hfFont), (rect.getLeft() + rect.getRight()) / 2,
                    rect.getBottom() - 18, 0);
        }
    });

    document.open();
    document.addAuthor("Let's Do It, Romania!");
    document.addTitle("Pachet mormane");
    document.addCreationDate();

    Font titleFont = new Font(bf, 24, Font.BOLD);
    Font noteFont = new Font(bf, 12, Font.NORMAL, BaseColor.RED);
    Font headerFont = new Font(bf, 12, Font.BOLD);
    Font normalFont = new Font(bf, 11);
    Font defFont = new Font(bf, 11, Font.BOLD);
    Paragraph par;
    int page = 0;

    for (Garbage garbage : garbages) {
        par = new Paragraph();
        par.setAlignment(Element.ALIGN_CENTER);
        par.add(new Chunk("Morman " + garbage.getGarbageId() + "\n", titleFont));
        par.add(new Chunk("Citi\u0163i cu aten\u0163ie!", noteFont));
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("1. Date generale\n", headerFont));
        par.add(new Chunk("Jude\u0163ul: ", defFont));
        par.add(new Chunk(garbage.getCounty().getName() + "\n", normalFont));
        par.add(new Chunk("Comuna: ", defFont));
        par.add(new Chunk(garbage.getTown().getName() + "\n", normalFont));
        if (garbage.getChartedArea() != null) {
            par.add(new Chunk("Zona cartare: ", defFont));
            par.add(new Chunk(garbage.getChartedArea().getName() + "\n", normalFont));
        }
        par.add(new Chunk("Pozi\u0163ie: ", defFont));
        par.add(new Chunk(garbage.getY() + ", " + garbage.getX() + "\n", normalFont));
        par.add(new Chunk("Descriere:\n", defFont));
        par.add(new Phrase(garbage.getDescription() + "\n", normalFont));
        par.add(new Chunk("Componen\u0163\u0103 gunoi:\n", defFont));
        List list = new List();
        list.add(new ListItem(
                new Chunk("Procent plastic: " + garbage.getPercentagePlastic() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent sticl\u0103: " + garbage.getPercentageGlass() + "%", normalFont)));
        list.add(new ListItem(new Chunk("Procent metale: " + garbage.getPercentageMetal() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent nereciclabile: " + garbage.getPercentageWaste() + "%", normalFont)));
        par.add(list);
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("2. Indica\u0163ii rutiere\n", headerFont));
        Image img = Image.getInstance(getImage(garbage));
        img.scaleToFit((float) (PageSize.A4.getWidth() * .75), (float) (PageSize.A4.getHeight() * .75));
        img.setAlignment(Element.ALIGN_CENTER);
        par.add(img);
        document.add(par);

        if (page < garbages.size() - 1)
            document.newPage();
        page++;
    }

    document.close();
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Draw an image on the current page.// ww w . j  ava  2 s. co  m
 * @param Writer PDF writer
 * @param Img Image data
 * @param x X coordinate of bottom left corner of image
 * @param y Y coordinate of bottom left corner of image
 * @param Width Image width
 * @param Height Image height
 * @throws BadElementException
 * @throws DocumentException 
 * @throws IOException
 * @throws MalformedURLException
 */
private void drawImage(PdfWriter Writer, File Img, int x, int y, int Width, int Height)
        throws BadElementException, MalformedURLException, IOException, DocumentException {
    // resize the image
    byte[] data = ImageUtils.resizeImageToByteArray(Img, Width, Height);
    // place the image
    Image img = Image.getInstance(data);
    img.setAbsolutePosition(x, y);
    Writer.getDirectContent().addImage(img, true);
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Draw a text label on the current page.
 * @param Writer PDF writer/*from   w  ww .j a  v a  2 s . c  om*/
 * @param Text
 * @param x
 * @param y
 * @param alignment
 * @throws DocumentException
 * @throws IOException 
 */
private void drawLabel(PdfWriter Writer, String Text, int x, int y, int alignment)
        throws DocumentException, IOException {
    PdfContentByte cb = Writer.getDirectContent();
    BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.saveState();
    cb.beginText();
    cb.setFontAndSize(bf, 9);
    cb.showTextAligned(alignment, Text, x, y, 0);
    cb.endText();
    cb.restoreState();
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Draw a line on the page//w  ww . j av  a2  s.co m
 * @param Writer
 * @param x1 Line start, X coordinate
 * @param y1 Line start, Y coordinate
 * @param x2 Line end, X coordinate
 * @param y2 Line end, Y coordinate
 * @param t Stroke thickness
 */
private static void drawLine(PdfWriter Writer, int x1, int y1, int x2, int y2, float t)
        throws DocumentException, IOException {
    PdfContentByte cb = Writer.getDirectContent();
    cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 24); // TODO why do we have this here??
    cb.moveTo(x1, y1);
    cb.lineTo(x2, y2);
    cb.setLineWidth(t);
    cb.stroke();
}