Search in sources :

Example 26 with Document

use of com.itextpdf.text.Document in project opentheso by miledrousset.

the class itextPdf method start_test.

@Test
public void start_test() throws DocumentException, FileNotFoundException {
    try {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream("test-itext.pdf"));
        // step 3
        document.open();
        String FONT = "fonts/FreeSans.ttf";
        BaseFont bf1 = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        Font french = new Font(bf1, 12);
        BaseFont bf2 = BaseFont.createFont(FONT, BaseFont.CP1250, BaseFont.EMBEDDED);
        Font czech = new Font(bf2, 12);
        BaseFont bf3 = BaseFont.createFont(FONT, "Cp1251", BaseFont.EMBEDDED);
        Font russian = new Font(bf3, 12);
        document.add(new Paragraph("Vous \u00eates d'o\u00f9?", french));
        document.add(new Paragraph("\u00c0 tout \u00e0 l'heure. \u00c0 bient\u00f4t.", french));
        document.add(new Paragraph("Je me pr\u00e9sente.", french));
        document.add(new Paragraph("C'est un \u00e9tudiant.", french));
        document.add(new Paragraph("\u00c7a va?", french));
        document.add(new Paragraph("Il est ing\u00e9nieur. Elle est m\u00e9decin.", french));
        document.add(new Paragraph("C'est une fen\u00eatre.", french));
        document.add(new Paragraph("R\u00e9p\u00e9tez, s'il vous pla\u00eet.", french));
        document.add(new Paragraph("Odkud jste?", czech));
        document.add(new Paragraph("Uvid\u00edme se za chvilku. M\u011bj se.", czech));
        document.add(new Paragraph("Dovolte, abych se p\u0159edstavil.", czech));
        document.add(new Paragraph("To je studentka.", czech));
        document.add(new Paragraph("V\u0161echno v po\u0159\u00e1dku?", czech));
        document.add(new Paragraph("On je in\u017een\u00fdr. Ona je l\u00e9ka\u0159.", czech));
        document.add(new Paragraph("Toto je okno.", czech));
        document.add(new Paragraph("Zopakujte to pros\u00edm.", czech));
        document.add(new Paragraph("\u041e\u0442\u043a\u0443\u0434\u0430 \u0442\u044b?", russian));
        document.add(new Paragraph("\u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f \u0432 \u043d\u0435\u043c\u043d\u043e\u0433\u043e. \u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f.", russian));
        document.add(new Paragraph("\u041f\u043e\u0437\u0432\u043e\u043b\u044c\u0442\u0435 \u043c\u043d\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c\u0441\u044f.", russian));
        document.add(new Paragraph("\u042d\u0442\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442.", russian));
        document.add(new Paragraph("\u0425\u043e\u0440\u043e\u0448\u043e?", russian));
        document.add(new Paragraph("\u041e\u043d \u0438\u043d\u0436\u0435\u043d\u0435\u0440. \u041e\u043d\u0430 \u0434\u043e\u043a\u0442\u043e\u0440.", russian));
        document.add(new Paragraph("\u042d\u0442\u043e \u043e\u043a\u043d\u043e.", russian));
        document.add(new Paragraph("\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435, \u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430.", russian));
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 30, Font.BOLD);
        document.add(new Paragraph("Title of the document", catFont));
        // step 4
        document.add(new Paragraph("Hello World!\n test \n                  test"));
        Chunk chunk = new Chunk("Go to Contact information");
        chunk.setLocalGoto("contact");
        document.add(new Paragraph(chunk));
        document.newPage();
        document.add(new Paragraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut consectetur, nisi non commodo interdum, nunc massa sodales velit, vel elementum ipsum odio id ligula. Aliquam sed sapien eget nibh varius varius id ac quam. Aliquam id arcu enim. Curabitur sollicitudin placerat dui, nec venenatis ipsum consectetur ut. Fusce sem nibh, semper et nibh sed, varius mattis ipsum. Duis tristique mauris velit. Nam eleifend sapien tempus, sollicitudin risus sit amet, dignissim nisl. Aliquam tincidunt rutrum auctor. Integer sollicitudin lectus faucibus ipsum facilisis imperdiet. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam erat volutpat. Etiam eu commodo massa, ac venenatis est. Sed venenatis mattis vehicula. Duis eleifend lacus nec purus convallis, non mollis justo commodo. Aenean et arcu vitae metus pharetra venenatis ac non tellus. Vestibulum ultrices turpis urna, vitae condimentum sem pharetra in.\n" + "\n" + "Maecenas aliquet auctor ipsum eget congue. Sed at ullamcorper ante. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse scelerisque at erat at condimentum. Vivamus sed aliquet risus, non tempor odio. Etiam pulvinar, mauris ut placerat consequat, ipsum massa imperdiet turpis, eget consequat justo metus sit amet ligula. Donec vel lacinia erat. Donec eget enim sed justo euismod vehicula ut in metus. Suspendisse augue dolor, tempor eu mollis vitae, pellentesque sit amet nulla. Morbi ac sapien arcu. Vivamus in elit dictum orci dapibus blandit eget vitae est. Morbi sed ultricies neque. Ut at fringilla urna. Quisque dictum bibendum nisi, non pellentesque velit cursus vel.\n" + "\n" + "Etiam convallis tincidunt arcu sit amet pellentesque. Suspendisse vitae gravida tellus. Fusce consectetur turpis condimentum, molestie libero pellentesque, aliquet dolor. Duis ullamcorper purus sem, id ornare lacus interdum non. Aenean quis arcu elementum, ultrices tellus sed, dapibus nisl. Aliquam ut iaculis mi, vitae porttitor tellus. Vestibulum lacinia velit sed venenatis volutpat. Nullam magna ipsum, feugiat vestibulum nunc tincidunt, egestas ultrices libero. Quisque fringilla risus ut lectus posuere vulputate. Fusce diam mi, efficitur vitae nulla eget, facilisis luctus nisi. Sed scelerisque hendrerit porttitor. Aenean mollis, urna in bibendum bibendum, lectus orci dictum sapien, ut pretium dui lacus vel turpis. Nunc hendrerit est sit amet turpis venenatis suscipit. Phasellus fermentum aliquam tellus nec sodales.\n" + "\n" + "Etiam eget scelerisque erat, nec commodo arcu. Nullam tempus vehicula auctor. Integer feugiat ornare viverra. In nulla arcu, faucibus ut risus malesuada, elementum egestas eros. Maecenas varius augue faucibus, vulputate turpis at, vestibulum nisi. Etiam placerat vehicula erat, ac viverra nulla interdum id. Sed nibh sem, bibendum ac sodales vitae, iaculis vel magna. Phasellus fringilla quis lectus ac egestas. Praesent iaculis, orci non ultrices mattis, urna ipsum suscipit tortor, nec viverra mi tortor id libero. Quisque vehicula malesuada elit, vitae interdum nunc. In laoreet viverra scelerisque. Nam venenatis blandit tortor, vel aliquam mi rutrum eget. In ut nibh ut nibh lobortis ullamcorper. Morbi neque elit, dictum vel justo nec, pulvinar fermentum purus. Sed consequat dictum hendrerit. Quisque pulvinar mi volutpat est aliquet facilisis.\n" + "\n" + "Phasellus ultrices euismod ligula, ac sagittis diam semper eu. Nulla aliquam justo vel leo congue condimentum. Fusce molestie tellus felis, vel fringilla mi molestie ac. Praesent venenatis sapien eget lectus gravida, vitae condimentum ligula sagittis. Mauris varius placerat sagittis. Phasellus eget tortor quis felis pellentesque malesuada pharetra a lectus. Sed rutrum mi id aliquam lacinia. Donec posuere auctor vulputate. Duis a ante id nisl cursus accumsan. "));
        Chunk chunk1 = new Chunk("Contact information");
        chunk1.setLocalDestination("contact");
        Chapter chapter = new Chapter(new Paragraph(chunk1), 1);
        chapter.setNumberDepth(0);
        document.add(chapter);
        PdfPTable table = new PdfPTable(2);
        table.addCell(new Paragraph("test 1", catFont));
        table.addCell("2");
        document.add(table);
        // step 5
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(itextPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : PdfPTable(com.itextpdf.text.pdf.PdfPTable) FileOutputStream(java.io.FileOutputStream) BaseFont(com.itextpdf.text.pdf.BaseFont) Chapter(com.itextpdf.text.Chapter) IOException(java.io.IOException) Document(com.itextpdf.text.Document) Chunk(com.itextpdf.text.Chunk) Font(com.itextpdf.text.Font) BaseFont(com.itextpdf.text.pdf.BaseFont) Paragraph(com.itextpdf.text.Paragraph) Test(org.junit.Test)

Example 27 with Document

use of com.itextpdf.text.Document in project pancm_project by xuwujing.

the class PdfUtils method generatePdfByTemplate.

// 利用模板生成pdf
public static void generatePdfByTemplate(Map<String, Object> o, String templatePath, String newPDFPath) {
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos;
    PdfStamper stamper;
    try {
        BaseFont bf = BaseFont.createFont("/home/release/file/upload/template/pdf/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font FontChinese = new Font(bf, 5, Font.NORMAL);
        // 输出流
        out = new FileOutputStream(newPDFPath);
        // 读取pdf模板
        reader = new PdfReader(templatePath);
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        // 文字类的内容处理
        Map<String, String> dataMap = (Map<String, String>) o.get("dataMap");
        form.addSubstitutionFont(bf);
        for (String key : dataMap.keySet()) {
            String value = dataMap.get(key);
            form.setField(key, value);
        }
        // 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
        stamper.setFormFlattening(true);
        stamper.close();
        Document doc = new Document();
        Font font = new Font(bf, 32);
        PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
        copy.addPage(importPage);
        doc.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(e);
    } catch (DocumentException e) {
        e.printStackTrace();
        System.out.println(e);
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Document(com.itextpdf.text.Document) Font(com.itextpdf.text.Font) FileOutputStream(java.io.FileOutputStream) DocumentException(com.itextpdf.text.DocumentException) Map(java.util.Map)

Example 28 with Document

use of com.itextpdf.text.Document in project propane by ruby-processing.

the class PGraphicsPDF method beginDraw.

@Override
public void beginDraw() {
    if (document == null) {
        ByteBuffer.HIGH_PRECISION = true;
        document = new Document(new Rectangle(width, height));
        boolean missingPath = false;
        try {
            if (file != null) {
                try {
                    output = new BufferedOutputStream(new FileOutputStream(file), 16384);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(PGraphicsPDF.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (output == null) {
                missingPath = true;
                throw new RuntimeException("PGraphicsPDF requires a path " + "for the location of the output file.");
            }
            try {
                writer = PdfWriter.getInstance(document, output);
            } catch (DocumentException ex) {
                Logger.getLogger(PGraphicsPDF.class.getName()).log(Level.SEVERE, null, ex);
            }
            document.open();
            content = writer.getDirectContent();
        // template = content.createTemplate(width, height);
        } catch (RuntimeException re) {
            if (missingPath) {
                // don't re-package our own error
                throw re;
            } else {
                throw new RuntimeException("Problem saving the PDF file.", re);
            }
        }
        g2 = new PdfGraphics2D(content, width, height);
    }
    // super in Java2D now creates an image buffer, don't do that
    // super.beginDraw();
    checkSettings();
    // reset model matrix
    resetMatrix();
    vertexCount = 0;
    pushMatrix();
}
Also used : FileOutputStream(java.io.FileOutputStream) DocumentException(com.itextpdf.text.DocumentException) Rectangle(com.itextpdf.text.Rectangle) FileNotFoundException(java.io.FileNotFoundException) PdfGraphics2D(com.itextpdf.awt.PdfGraphics2D) Document(com.itextpdf.text.Document) BufferedOutputStream(java.io.BufferedOutputStream)

Example 29 with Document

use of com.itextpdf.text.Document in project tutorials by eugenp.

the class PDF2TextExample method generatePDFFromTxt.

private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
    Document pdfDoc = new Document(PageSize.A4);
    PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf")).setPdfVersion(PdfWriter.PDF_VERSION_1_7);
    pdfDoc.open();
    Font myfont = new Font();
    myfont.setStyle(Font.NORMAL);
    myfont.setSize(11);
    pdfDoc.add(new Paragraph("\n"));
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String strLine;
    while ((strLine = br.readLine()) != null) {
        Paragraph para = new Paragraph(strLine + "\n", myfont);
        para.setAlignment(Element.ALIGN_JUSTIFIED);
        pdfDoc.add(para);
    }
    pdfDoc.close();
    br.close();
}
Also used : FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) COSDocument(org.apache.pdfbox.cos.COSDocument) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) Document(com.itextpdf.text.Document) Font(com.itextpdf.text.Font) Paragraph(com.itextpdf.text.Paragraph)

Example 30 with Document

use of com.itextpdf.text.Document in project specify by rhebecaabreu.

the class DocumentoReq method criaPDF.

/**
 * @param args
 * @throws FileNotFoundException
 * @throws DocumentException
 * @throws IOException
 * @throws MalformedURLException
 */
public void criaPDF(JTable table_1, java.util.List<Integer> codigosReq) throws FileNotFoundException, DocumentException {
    // Listing 1. Instantiation of document object
    Document document = new Document();
    try {
        document.setPageSize(PageSize.A4);
        document.setMargins(50, 50, 50, 50);
        nomepdf = MeusProjetos.getNome_pdf() + ".pdf";
        // Listing 2. Creation of PdfWriter object
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nomepdf));
        ModelPDFRodape mf = new ModelPDFRodape();
        mf.setTopo("Specify");
        writer.setPageEvent(mf);
        document.open();
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date date = new Date();
        String data = dateFormat.format(date);
        // Listing 3. Creation of chapter object
        Paragraph title1 = new Paragraph("JTFieldOnlyNumbers de Requisitos", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
        title1.setAlignment(Element.ALIGN_CENTER);
        Chapter chapter1 = new Chapter(title1, 1);
        chapter1.setNumberDepth(0);
        RequisitoDAO rdao = new RequisitoDAO();
        // Listing 4. Creation of section object
        ProjetoDAO pread = new ProjetoDAO();
        for (Requisito r : rdao.readOrderBy()) {
            for (Projeto p : pread.read()) {
                for (int i = 0; i < codigosReq.size(); i++) {
                    if (r.getProjcodigo() == p.getCodigo() && r.getCodigo() == codigosReq.get(0)) {
                        Paragraph title_project2 = new Paragraph("Projeto: " + p.getNome(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));
                        title_project2.setAlignment(Element.ALIGN_CENTER);
                        chapter1.add(title_project2);
                        break;
                    }
                }
            }
        }
        Paragraph data_hora = new Paragraph("Gerado em " + data, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.NORMAL));
        data_hora.setAlignment(Element.ALIGN_CENTER);
        chapter1.add(data_hora);
        Paragraph listRequirement = new Paragraph("Lista de Requisitos", FontFactory.getFont(FontFactory.HELVETICA, 14, Font.NORMAL));
        Section section1 = chapter1.addSection(listRequirement);
        RequisitoDAO rrdao = new RequisitoDAO();
        Font f = FontFactory.getFont(FontFactory.HELVETICA, 13, Font.NORMAL);
        Font ff = FontFactory.getFont(FontFactory.HELVETICA, 13, Font.BOLD);
        for (Requisito r : rrdao.readOrderBy()) {
            if (table_1.getSelectedRow() != -1) {
                for (int j = 0; j < (codigosReq.size()); j++) {
                    if (r.getCodigo() == codigosReq.get(j)) {
                        if (r.getTipoReq().toString().equals("FUNCIONAL")) {
                            Paragraph o = new Paragraph();
                            o.setFont(ff);
                            o.add("Tipo de Requisito: ");
                            o.setFont(f);
                            o.add("Funcional" + "       ");
                            o.setFont(ff);
                            o.add(" Código: ");
                            o.setFont(f);
                            o.add(String.valueOf(r.getCodigo()));
                            section1.add(o);
                        }
                        if (r.getTipoReq().toString().equals("NAOFUNCIONAL")) {
                            Paragraph o = new Paragraph();
                            o.setFont(ff);
                            o.add("Tipo de Requisito: ");
                            o.setFont(f);
                            o.add("Não-funcional" + "       ");
                            o.setFont(ff);
                            o.add(" Código: ");
                            o.setFont(f);
                            o.add(String.valueOf(r.getCodigo()));
                            section1.add(o);
                        }
                        if (r.getTipoReq().toString().equals("USUARIO")) {
                            Paragraph o = new Paragraph();
                            o.setFont(ff);
                            o.add("Tipo de Requisito: ");
                            o.setFont(f);
                            o.add("       Usuário" + "       ");
                            o.setFont(ff);
                            o.add(" Código: ");
                            o.setFont(f);
                            o.add(String.valueOf(r.getCodigo()));
                            section1.add(o);
                        }
                        if (r.getTipoReq().toString().equals("NEGOCIO")) {
                            Paragraph o = new Paragraph();
                            o.setFont(ff);
                            o.add("Tipo de Requisito: ");
                            o.setFont(f);
                            o.add("       Negócio" + "       ");
                            o.setFont(ff);
                            o.add(" Código: ");
                            o.setFont(f);
                            o.add(String.valueOf(r.getCodigo()));
                            section1.add(o);
                        }
                        Paragraph p = new Paragraph();
                        Paragraph q = new Paragraph();
                        Paragraph rr = new Paragraph();
                        Paragraph s = new Paragraph();
                        Paragraph t = new Paragraph();
                        p.setFont(ff);
                        p.add("Identificador: ");
                        p.setFont(f);
                        p.add(r.getId());
                        q.setFont(ff);
                        q.add("O(a) " + r.getSujeito() + " deve ser capaz de " + r.getAcaoRestricao() + " para " + r.getValorRazao());
                        rr.setFont(ff);
                        rr.add("Grau Prioridade: ");
                        rr.setFont(f);
                        rr.add(r.getGrauPrioridade().toString());
                        s.setFont(ff);
                        s.add("Grau Dificuldade: ");
                        s.setFont(f);
                        s.add(r.getGrauDificuldade().toString());
                        t = new Paragraph(" ");
                        section1.add(p);
                        section1.add(q);
                        section1.add(rr);
                        section1.add(s);
                        section1.add(t);
                    }
                }
            }
        }
        // Listing 5. Addition of a chapter to the main document
        document.add(chapter1);
        document.add(Chunk.NEXTPAGE);
    } catch (DocumentException ex) {
        System.out.println("Error:" + ex);
    } catch (FileNotFoundException ex) {
        System.out.println("Error:" + ex);
    } finally {
        document.close();
    }
    try {
        Desktop.getDesktop().open(new File(nomepdf));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : PdfWriter(com.itextpdf.text.pdf.PdfWriter) Requisito(model.bean.Requisito) ModelPDFRodape(model.bean.ModelPDFRodape) Chapter(com.itextpdf.text.Chapter) FileNotFoundException(java.io.FileNotFoundException) Projeto(model.bean.Projeto) IOException(java.io.IOException) Document(com.itextpdf.text.Document) Section(com.itextpdf.text.Section) Date(java.util.Date) Font(com.itextpdf.text.Font) Paragraph(com.itextpdf.text.Paragraph) RequisitoDAO(model.dao.RequisitoDAO) FileOutputStream(java.io.FileOutputStream) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) DocumentException(com.itextpdf.text.DocumentException) ProjetoDAO(model.dao.ProjetoDAO) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Aggregations

Document (com.itextpdf.text.Document)32 FileOutputStream (java.io.FileOutputStream)25 PdfWriter (com.itextpdf.text.pdf.PdfWriter)22 IOException (java.io.IOException)12 DocumentException (com.itextpdf.text.DocumentException)10 Rectangle (com.itextpdf.text.Rectangle)10 PdfContentByte (com.itextpdf.text.pdf.PdfContentByte)10 File (java.io.File)10 Font (com.itextpdf.text.Font)8 Paragraph (com.itextpdf.text.Paragraph)8 PdfTemplate (com.itextpdf.text.pdf.PdfTemplate)6 FileNotFoundException (java.io.FileNotFoundException)6 Graphics2D (java.awt.Graphics2D)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 PdfGraphics2D (com.itextpdf.awt.PdfGraphics2D)4 Chapter (com.itextpdf.text.Chapter)4 PdfPTable (com.itextpdf.text.pdf.PdfPTable)4 OutputStream (java.io.OutputStream)4 SimpleDateFormat (java.text.SimpleDateFormat)4 Date (java.util.Date)4