Example usage for com.itextpdf.text Document open

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

Introduction

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

Prototype

boolean open

To view the source code for com.itextpdf.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w.  j a va2 s .c o 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);
    }
}

From source file:com.dev.saurabh.TiffToPdf.java

License:Open Source License

/**
 * @param args//from   w  w  w .j  ava  2s  .com
 * @throws DocumentException
 * @throws IOException
 */
public static void main(String[] args) throws DocumentException, IOException {

    String imgeFilename = "/home/saurabh/Downloads/image.tif";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream("/home/saurabh/Desktop/out" + Math.random() + ".pdf"));
    writer.setStrictImageSequence(true);
    document.open();

    document.add(new Paragraph("Multipages tiff file"));
    Image image;
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(ra, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.add(image);
        document.newPage();
    }

    document.close();

}

From source file:com.devox.GUI.PDF.CrearReportePorEstado.java

@Override
public void crear(File file) {
    try {//from  w  w w.  j  a v a 2 s  .com
        Document document = new Document(PageSize.A4, 50f, 50f, 65f, 100f);
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina event = new CabeceraPieDePagina();
        w.setPageEvent(event);
        document.newPage();
        document.add(configurarInformacion());
        document.add(new Paragraph("\n"));
        PdfPTable table = crearTabla();
        agregarProductos(table);
        document.add(table);
        document.add(new Paragraph("\n"));
        document.add(new Paragraph("TOTAL: " + data.length + "FOLIOS.", FUENTE_FOLIO_CHICA));
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
    }

    Object[] options = { "Abrir PDF", "No" };
    int open = JOptionPane.showOptionDialog(null, "Desea abrir el reporte?", "Reporte guardado",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            new javax.swing.ImageIcon(getClass().getResource("/com/devox/GUI/images/print.png")), options,
            options[0]);
    if (open == JOptionPane.YES_OPTION) {
        try {
            Desktop.getDesktop().open(file);
        } catch (IOException ex) {
            Log.print("No se encontr la ruta");
            JOptionPane.showMessageDialog(null, "Error en el archivo");
        }
    }
}

From source file:com.devox.GUI.PDF.CrearReporteTarimas.java

@Override
public void crear(File file) {
    try {/*  ww  w  .ja  v  a  2  s.c o  m*/
        Document document = new Document(PageSize.A4.rotate());
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina event = new CabeceraPieDePagina();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 50);
        document.newPage();
        document.add(configurarInformacion());
        PdfPTable table = crearTabla();
        agregarProductos(table);
        document.add(table);
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
    }

    Object[] options = { "Abrir PDF", "No" };
    int open = JOptionPane.showOptionDialog(null, "Desea abrir el reporte?", "Reporte guardado",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            new javax.swing.ImageIcon(getClass().getResource("/com/devox/GUI/images/print.png")), options,
            options[0]);
    if (open == JOptionPane.YES_OPTION) {
        try {
            Desktop.getDesktop().open(file);
        } catch (IOException ex) {
            Log.print("No se encontr la ruta");
            JOptionPane.showMessageDialog(null, "Error en el archivo");
        }
    }
}

From source file:com.devox.GUI.PDF.ExportarAPDF.java

public void crearDestruccion(File file) {
    try {//from w  ww .j a  v a2  s  .c om
        Document document = new Document(PageSize.A4);
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina event = new CabeceraPieDePagina();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 220);
        document.newPage();
        document.add(setUpInformation());
        PdfPTable t = createTable();
        addProductos(model, t);
        document.add(t);
        //
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
        Log.print(ex);
    }
}

From source file:com.devox.GUI.PDF.ExportarAPDF.java

public void crearApto(File file) {
    try {/* w  ww  .j  av a  2 s .  c o  m*/
        Document document = new Document(PageSize.A4);
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina event = new CabeceraPieDePagina();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 220);
        document.newPage();
        document.add(setUpInformationTarimas());
        //            PdfPTable t = createTable();
        //            addProductos(model, t);
        //            document.add(t);
        //
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
        Log.print(ex);
    }
}

From source file:com.devox.GUI.PDF.ExportarAPDF.java

public void crearTarimas(File file) {
    try {//from  w w  w  .  j  a  v a2  s.c  om
        Document document = new Document(PageSize.A4.rotate());
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina2 event = new CabeceraPieDePagina2();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 50);
        document.newPage();
        document.add(setUpInformationTarimas());
        PdfPTable t = createTableTarimas();
        addProductosTarimas(t);
        document.add(t);
        //
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
        Log.print(ex);
    }
}

From source file:com.dexter.fms.mbean.ReportsMBean.java

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {/*from w  w w . ja  va2s  .  co  m*/
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FMS");
        document.addCreationDate();
        document.addCreator("FMS");
        document.addSubject("Report");
        document.addTitle(getReport_title());

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put("partner", dashBean.getUser().getPartner());
        GeneralDAO gDAO = new GeneralDAO();
        Object pSettingsObj = gDAO.search("PartnerSetting", params);
        PartnerSetting setting = null;
        if (pSettingsObj != null) {
            Vector<PartnerSetting> pSettingsList = (Vector<PartnerSetting>) pSettingsObj;
            for (PartnerSetting e : pSettingsList) {
                setting = e;
            }
        }
        gDAO.destroy();

        PdfPCell c = null;
        if (setting != null && setting.getLogo() != null) {
            Image logoImg = Image.getInstance(setting.getLogo());
            logoImg.scaleToFit(212, 51);
            c = new PdfPCell(logoImg);
        } else
            c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(getReport_title(), font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (getReport_start_dt() != null && getReport_end_dt() != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("From " + getReport_start_dt() + " to " + getReport_end_dt(), font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = exportPDFTable(type);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();
        String fileName = filename + ".pdf";

        writeFileToResponse(context.getExternalContext(), baos, fileName, "application/pdf");

        context.responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dexter.fuelcard.mbean.UtilMBean.java

public byte[] createInvoicePDF(int pageType, String title, String dateperiod, String amount, String chargeType,
        String chargeAmount, String total) {
    try {/*from   ww w  . j ava  2  s. co  m*/
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FUELCARD");
        document.addCreationDate();
        document.addCreator("FUELCARD");
        document.addSubject("Invoice");
        document.addTitle(title);

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        PdfPCell c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(title, font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (dateperiod != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("For " + dateperiod, font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = new PdfPTable(4);
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
        }
        font = new Font(helvetica, 8, Font.BOLDITALIC);

        pdfTable.addCell(new Paragraph("Charge Type", font)); // % per transaction or flat per license
        pdfTable.addCell(new Paragraph("Charge Amount", font)); // the amount of the charge setting

        if (chargeType.equalsIgnoreCase("Percent-Per-Tran")) {
            pdfTable.addCell(new Paragraph("Total Amount", font)); // the amount of the charge setting
        } else {
            pdfTable.addCell(new Paragraph("Total License", font)); // the amount of the charge setting
        }
        //pdfTable.addCell(new Paragraph("Description", font)); // the 
        pdfTable.addCell(new Paragraph("Amount Due", font));

        font = new Font(helvetica, 8, Font.NORMAL);
        pdfTable.addCell(new Paragraph(chargeType, font));
        pdfTable.addCell(new Paragraph(chargeAmount, font));
        pdfTable.addCell(new Paragraph(total, font));
        pdfTable.addCell(new Paragraph(amount, font));

        pdfTable.setWidthPercentage(100);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();

        return baos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public InputStream generateBlockTitleToPDF(InputStream inputStream) throws IOException, DocumentException {

    File tmpDir = com.google.common.io.Files.createTempDir();
    File blockTitleFile = new File(tmpDir, inputStream.toString());

    ResourceBundle bundle = ResourceBundle.getBundle(BASE_NAME, pLocale);

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(blockTitleFile));
    document.open();

    // Main paragraph
    Paragraph preface = new Paragraph();
    generateHeader(preface, bundle);/*from  w ww  . j  a v a2  s  .co  m*/
    generateTable(preface, bundle);
    addEmptyLine(preface, 1);
    if (!instanceAttributes.isEmpty()) {
        generateAttribute(preface, bundle);
        addEmptyLine(preface, 1);
    }
    if (workflow != null) {
        generateLyfeCycleState(preface, bundle);
    }

    document.add(preface);

    addMetaData(document);

    document.close();

    tmpDir.deleteOnExit();

    // Merge the pdf generated with the pdf given in the input stream
    //TODO: use PdfStamper to insert into the existing pdf.
    return mergePdfDocuments(new FileInputStream(blockTitleFile), inputStream);

}