Example usage for com.itextpdf.text Document Document

List of usage examples for com.itextpdf.text Document Document

Introduction

In this page you can find the example usage for com.itextpdf.text Document Document.

Prototype


public Document() 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioBalancoProdutos(Date inicio, Date fim, File destino) {
    Document doc = new Document();
    try {//from   w ww.j a v  a  2  s.c om
        String path = a.getRelatorio().getCanonicalPath() + destino.getName();
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Sada de produtos \n Refernte do dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(inicio) + " ao dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(fim);
        inserirHead(doc, "Balano de Produtos", subTitulo);

        PdfPTable table = getTableBalancoProdutos(inicio, fim);

        doc.add(table);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfDaVenda(Venda v, List<ItemDeVenda> itens, File destino) throws IOException {
    Document doc = new Document();

    try {/*from   www.  j  ava  2 s  .co m*/
        String path = a.getRelatorio().getCanonicalPath() + "/Venda_" + v.getId() + ".pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Venda Realizada no dia "
                + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(v.getDia().getTime());
        try {
            inserirHead(doc, "Venda do Cliente " + v.getCliente().getNome(), subTitulo);
        } catch (NullPointerException ne) {
            inserirHead(doc, "Venda  vista ID: " + v.getId(), subTitulo);
        }

        PdfPTable table = getTableDeItens(itens);

        doc.add(table);

        Paragraph p2 = new Paragraph("Total: " + new DecimalFormat("0.00").format(v.getTotal())
                + " \n Funcionrio: " + v.getFuncionario().getNome(),
                new Font(Font.FontFamily.COURIER, 16, Font.BOLD));
        doc.add(p2);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioBalancoProdutos(Date inicio, Date fim) {
    Document doc = new Document();
    try {//ww w.  jav  a2 s .  co m
        String path = a.getRelatorio().getCanonicalPath() + "/RelatorioBalancoProdutos.pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Sada de produtos \n Refernte do dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(inicio) + " ao dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(fim);
        inserirHead(doc, "Balano de Produtos", subTitulo);

        PdfPTable table = getTableBalancoProdutos(inicio, fim);

        doc.add(table);

        doc.close();
        return path;
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfDaVenda(Venda v, List<ItemDeVenda> itens) {
    Document doc = new Document();

    try {//from  w  w w  . j  a va 2 s .  c o m
        String path = a.getRelatorio().getCanonicalPath() + "/Venda_" + v.getId() + ".pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Venda Realizada no dia "
                + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(v.getDia().getTime());
        if (v.getCliente() != null) {
            inserirHead(doc, "Venda do Cliente " + v.getCliente().getNome(), subTitulo);
        } else {//venda a vista
            inserirHead(doc, "Venda  Vista", subTitulo);
        }

        PdfPTable table = getTableDeItens(itens);

        doc.add(table);

        Paragraph p2 = new Paragraph("Total: " + new DecimalFormat("0.00").format(v.getTotal())
                + " \n Funcionrio: " + v.getFuncionario().getNome(),
                new Font(Font.FontFamily.COURIER, 16, Font.BOLD));
        doc.add(p2);

        doc.close();
        return path;
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method Generate the shipping label as a PDF file
 * @throws InterruptedException //ww w  . j a  va2s.c  o m
 * @throws URISyntaxException 
 */
private String generateShippingLabelPDF(byte[] decoded, String trackingNumber, ShippingInfoDO shippingInfoDO,
        ShipmentRequest request)
        throws MalformedURLException, IOException, DocumentException, InterruptedException, URISyntaxException {
    Document document = new Document();
    PdfWriter writer;
    String URL = "";
    try {
        String filename = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath()
                + trackingNumber + ShippingConstants.PDF_fILE;
        String path = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + trackingNumber
                + ShippingConstants.PNG_FILE;
        if (genReturnLabel) {
            filename = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + "Return_"
                    + trackingNum + ShippingConstants.PDF_fILE;
            path = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + "Return_"
                    + trackingNum + ShippingConstants.PNG_FILE;
        } else {
            trackingNum = trackingNumber;
        }
        filename = filename.replace(ShippingConstants.FILE_PATH, ShippingConstants.File_Path_Replace);
        path = path.replace(ShippingConstants.FILE_PATH, ShippingConstants.File_Path_Replace);
        OutputStream out1 = null;

        try {
            out1 = new BufferedOutputStream(new FileOutputStream(path));
            out1.write(decoded);
        } finally {
            if (out1 != null) {
                out1.close();
            }
        }
        //URL = createInvoicePDF(path, filename);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return URL;
}

From source file:com.datamyne.charts.AlmostThereDemo.java

License:Apache License

/**
 * Creates PDf file.//from   www . j  a va 2 s  . com
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this
        //add the PdfTemplate to the PdfContentByte
        contentByte.addTemplate(template, 0, 300);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.FinallyDemo.java

License:Apache License

/**
 * Creates PDf file./*from  w w  w. j  a v a2s  .c o m*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //get dummy text
        String text = getText();
        //create text font
        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFamily.TIMES_ROMAN, 10.0f);

        //add text before
        document.add(new Paragraph(new Chunk(text, font)));

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this

        //create Image from PdfTemplate
        Image image = Image.getInstance(template);
        document.add(image);

        //add text after
        document.add(new Paragraph(new Chunk(text, font)));

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.FixingUglyDemoByScaling.java

License:Apache License

/**
 * Creates PDf file./*from   w  ww . ja v  a 2s  .c om*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        float fWidth = 0.6f * width;
        float fHeight = 0.6f * height;
        JFreeChart chart = getChart();
        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        image.scaleAbsolute(fWidth, fHeight);
        document.add(image);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.UglyDemo.java

License:Apache License

/**
 * Creates PDf file./*from   w w  w.j  av  a 2 s.  c  om*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();
        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        document.add(image);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.deadormi.servlet.CreaPdfServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww  . j a va  2  s  .  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = request.getQueryString();
    Integer gruppo_id = Integer.parseInt(url.substring(url.indexOf("=") + 1, url.length()));

    List<Utente> iscritti = null;
    List<Post> posts = null;
    Gruppo gruppo = null;
    Utente utente = null;
    String imageUrl = null;
    String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

    try {
        iscritti = UtenteController.getUserByGroupId(request, gruppo_id);
        gruppo = GruppoController.getGruppoById(request, gruppo_id);
    } catch (SQLException ex) {
        log.error(ex);
    }

    // step 1: creation of a document-object
    Document document = new Document();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();

        String incipit = "Report del " + CurrentDate.getCurrentDate() + "\n";
        Paragraph pIncipit = new Paragraph(incipit,
                FontFactory.getFont(FontFactory.HELVETICA, 14, BaseColor.BLACK));
        pIncipit.setAlignment(Element.ALIGN_CENTER);
        pIncipit.setSpacingAfter(10);
        document.add(pIncipit);

        String title = "Gruppo " + gruppo.getNome();
        Paragraph pTitle = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 18, BaseColor.BLUE));
        pTitle.setAlignment(Element.ALIGN_CENTER);
        pTitle.setSpacingAfter(40);
        document.add(pTitle);

        PdfPCell labelNome = new PdfPCell(new Paragraph("Nome utente"));
        PdfPCell labelNumPost = new PdfPCell(new Paragraph("Num. post"));
        PdfPCell labelData = new PdfPCell(new Paragraph("Data ultimo post"));
        labelNome.setBorder(Rectangle.NO_BORDER);
        labelNumPost.setBorder(Rectangle.NO_BORDER);
        labelData.setBorder(Rectangle.NO_BORDER);

        for (int i = 0; i < iscritti.size(); i++) {
            utente = iscritti.get(i);
            try {
                posts = PostController.getPostByGruppoIdAndUserId(request, gruppo_id, utente.getId_utente());
            } catch (SQLException ex) {
                Logger.getLogger(CreaPdfServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (utente.getNome_avatar() != null) {
                imageUrl = baseUrl + request.getContextPath() + AVATAR_RESOURCE_PATH + "/"
                        + utente.getId_utente() + "_" + utente.getNome_avatar();
                ;
            } else {
                imageUrl = baseUrl + request.getContextPath() + "/res/images/user_avatar.png";
            }
            Image image = Image.getInstance(new URL(imageUrl));
            image.scaleToFit(50, 50);

            PdfPTable table = new PdfPTable(3);

            PdfPCell cellAvatar = new PdfPCell(image);
            cellAvatar.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAvatar.setBorder(Rectangle.NO_BORDER);
            cellAvatar.setRowspan(3);

            PdfPCell cellNome = new PdfPCell(new Paragraph(utente.getUsername() + ""));
            cellNome.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellNumPost = new PdfPCell(new Paragraph(posts.size() + ""));
            cellNumPost.setBorder(Rectangle.NO_BORDER);

            //L'ultimo  sempre il piu recente siccome la query  ORDER BY data_creazione
            PdfPCell cellData;
            if (posts.size() != 0) {
                cellData = new PdfPCell(new Paragraph(posts.get(posts.size() - 1).getData_creazione()));
            } else {
                cellData = new PdfPCell(new Paragraph("N/A"));

            }
            cellData.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellVoidBottom = new PdfPCell(new Paragraph(" "));
            cellVoidBottom.setBorder(Rectangle.BOTTOM);
            cellVoidBottom.setPaddingBottom(10);
            cellVoidBottom.setColspan(3);

            PdfPCell cellVoidTop = new PdfPCell(new Paragraph(" "));
            cellVoidTop.setBorder(Rectangle.NO_BORDER);
            cellVoidTop.setPaddingTop(10);
            cellVoidTop.setColspan(3);

            table.addCell(cellVoidTop);
            table.addCell(cellAvatar);
            table.addCell(labelNome);
            table.addCell(cellNome);
            table.addCell(labelNumPost);
            table.addCell(cellNumPost);
            table.addCell(labelData);
            table.addCell(cellData);
            table.addCell(cellVoidBottom);

            document.add(table);

        }

        document.close();
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "inline; filename=ahahah.pdf");
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch (DocumentException ex) {
        Logger.getLogger(CreaPdfServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}