Example usage for com.itextpdf.text.pdf PdfContentByte addTemplate

List of usage examples for com.itextpdf.text.pdf PdfContentByte addTemplate

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte addTemplate.

Prototype

public void addTemplate(final PdfTemplate template, final double x, final double y) 

Source Link

Document

Adds a template to this content.

Usage

From source file:cis_690_report.DynamicReporter.java

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed

    // TODO add your handling code here:
    // build a controller
    SwingController controller = new SwingController();

    // Build a SwingViewFactory configured with the controller
    SwingViewBuilder factory = new SwingViewBuilder(controller);

    // Use the factory to build a JPanel that is pre-configured
    //with a complete, active Viewer UI.
    JPanel viewerComponentPanel = factory.buildViewerPanel();

    // add copy keyboard command
    ComponentKeyBinding.install(controller, viewerComponentPanel);

    // add interactive mouse link annotation support via callback
    controller.getDocumentViewController().setAnnotationCallback(
            new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController()));

    // Create a JFrame to display the panel in
    JFrame window = new JFrame("Using the Viewer Component");
    window.getContentPane().add(viewerComponentPanel);
    window.pack();//from   w  w w  .jav  a2  s. c  om
    window.setVisible(true);

    String Path;
    Path = "C:/Users/Shubh Chopra/Documents/reporter.pdf";

    try {
        br1 = new BufferedReader(new FileReader(f));
        BufferedReader b1 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {

    }

    String line = "";

    bull1 = new String[number_of_rows - 1][];
    int k = 0;
    BufferedReader br3 = null;
    try {
        br3 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {
    }
    try {
        while ((line = br3.readLine()) != null) {

            // use comma as separator
            String Bull[] = line.split(",");
            if (k != 0) {
                System.out.println(Bull.length);
                bull1[k - 1] = new String[Bull.length];
                for (int j = 0; j < Bull.length; j++) {

                    bull1[k - 1][j] = Bull[j];

                }
            }
            k++;
        }
    } catch (IOException ex) {
    }
    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
        Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

        //file path

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path));

        //document header attributes
        doc.addAuthor("Shubh Chopra");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("Shubh Chopra");
        doc.addTitle("BES");
        doc.setPageSize(PageSize.LETTER.rotate());

        //open document
        doc.open();
        //create a paragraph
        Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
        paragraph.setFont(bfBold20);
        paragraph.setAlignment(Element.ALIGN_CENTER);

        Image img = Image.getInstance("VETMED.png");

        img.scaleToFit(300f, 150f);
        doc.add(paragraph);
        PdfPTable table1 = new PdfPTable(2);
        table1.setWidthPercentage(100);
        PdfPCell cell = new PdfPCell(img);
        cell.setBorder(PdfPCell.NO_BORDER);
        table1.addCell(cell);

        String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";

        table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
        doc.add(table1);

        //specify column widths
        int temp = dlm2.size();

        float[] columnWidths = new float[temp];
        for (int x = 0; x < columnWidths.length; x++) {
            columnWidths[x] = 2f;
        }

        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(90f);
        DynamicReporter re;
        re = new DynamicReporter();

        for (int i = 0; i < dlm2.size(); i++) {
            String[] parts = dlm2.get(i).toString().split(": ");
            String part2 = parts[1];

            re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
        }

        table.setHeaderRows(1);
        //insert an empty row

        //create section heading by cell merging

        //just some random data to fill 

        for (int x = 0; x < dlm3.size(); x++) {
            String str = dlm3.get(x).toString();

            System.out.println(str);
            String[] parts = str.split(":");

            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            for (int i = 0; i < dlm2.getSize(); i++)
                for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                    String str1 = dlm2.get(i).toString();
                    String[] p1 = str1.split(": ");
                    String p2 = p1[0];
                    if (p2.equals(header[j])) {
                        re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                    }
                }
            // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
        }

        doc.add(table);
        if (jCheckBox2.isSelected()) {
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            for (int i = 0; i < dlm3.size(); i++) {

                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }

            }
            JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                    "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

            if (dlm3.size() > 12) {
                doc.newPage();
            }
            PdfContentByte contentByte = docWriter.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(325, 250);
            PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

            chart.draw(graphics2d, rectangle2d);

            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        }
        if (jCheckBox1.isSelected()) {

            for (int i = 0; i < dlm3.size(); i++) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }
                JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                        "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);

                doc.newPage();
            }
        }

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (doc != null) {
            //close the document
            doc.close();
        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

    }
    controller.openDocument(Path);
}

From source file:co.com.realtech.mariner.util.files.PDFUtils.java

public static File agregarTexto(byte[] bytes, String text) {
    File temp = null;/*from   w  w w  .  j  av a 2s  .  c o m*/
    try {
        temp = File.createTempFile("archivo", ".pdf");
        OutputStream oos = new FileOutputStream(temp);
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, oos);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        //InputStream targetStream = new FileInputStream(initialFile);
        // Load existing PDF
        PdfReader reader = new PdfReader(bis);
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        // Copy first page of existing PDF into output PDF
        document.setPageSize(reader.getPageSize(1));
        document.newPage();
        cb.addTemplate(page, 0, 0);

        ColumnText ct = new ColumnText(cb);
        Phrase myText = new Phrase(text);
        Font fuente = new Font();
        fuente.setSize(6);
        myText.setFont(fuente);
        ct.setSimpleColumn(myText, 0, -1, document.right(), document.top(), -10, Element.ALIGN_RIGHT);
        ct.go();

        ColumnText ct2 = new ColumnText(cb);
        Phrase myText2 = new Phrase(text);
        Font fuente2 = new Font();
        fuente2.setSize(6);
        myText2.setFont(fuente);
        ct2.setSimpleColumn(myText, 0, -1, document.right(), document.top(), 248, Element.ALIGN_RIGHT);
        ct2.go();

        ColumnText ct3 = new ColumnText(cb);
        Phrase myText3 = new Phrase(text);
        Font fuente3 = new Font();
        fuente3.setSize(6);
        myText3.setFont(fuente);
        ct3.setSimpleColumn(myText, 0, -1, document.right(), document.top(), 505, Element.ALIGN_RIGHT);
        ct3.go();

        document.close();
    } catch (Exception e) {
        System.out.println("e = " + e);
    }
    return temp;
}

From source file:com.automaster.autoview.server.servlet.TextStateOperators.java

/**
 * Creates a PDF document./*  ww  w . j a va  2  s.  c  o  m*/
 * @param filename the path to the new PDF document
 * @throws DocumentException 
 * @throws IOException
 */
public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(595, 842);
    Document document = new Document(rect, 30, 30, 30, 30);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    //PdfAcroForm canva = writer.getAcroForm();

    BaseFont bf = BaseFont.createFont();

    //canva.addMultiLineTextField("txtTeste", "texto de teste vamos ver se le quebra a linha", bf, 15, 300, 800, 100, 100);

    PdfContentByte canvas = writer.getDirectContent();
    String text = "AWAY again";
    String text1 = "TESTE Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto adriano";
    canvas.beginText();
    // line 1
    canvas.setFontAndSize(bf, 16);
    canvas.moveText(36, 800);
    canvas.moveTextWithLeading(0, -24);
    canvas.setTextRise(10);
    canvas.showText(text);
    // line 2
    canvas.setWordSpacing(20);
    canvas.newlineShowText(text);
    // line 3
    canvas.setCharacterSpacing(10);
    canvas.newlineShowText(text);
    canvas.setWordSpacing(0);
    canvas.setCharacterSpacing(0);
    // line 4
    canvas.setHorizontalScaling(50);
    canvas.newlineShowText(text);
    canvas.setHorizontalScaling(100);
    // line 5
    canvas.newlineShowText(text);
    canvas.setTextRise(15);
    canvas.setFontAndSize(bf, 12);
    canvas.setColorFill(BaseColor.RED);
    canvas.showText("2");
    canvas.setColorFill(GrayColor.GRAYBLACK);
    // line 6
    canvas.setLeading(56);
    canvas.setMiterLimit(5);
    canvas.newlineShowText(
            "Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto" + text);
    canvas.setLeading(24);
    canvas.newlineText();
    Paragraph paragraph = new Paragraph("teste");
    PdfWriter pdfWriter = canvas.getPdfWriter();
    PdfAcroForm pdfAcroForm = pdfWriter.getAcroForm();
    //pdfAcroForm.addMultiLineTextField("txtTeste", "Changing the adriano leading: Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto", bf, 12, 30, 650, 550, 750);
    //pdfAcroForm.addHiddenField("txtTeste", text); 
    PdfFormField pdfFormField = new PdfFormField(pdfWriter, 30, 650, 550, 750, null);
    pdfFormField.setFieldName("txtTeste");
    pdfFormField.setValueAsString(text1);
    //TextField textField = new TextField(canvas.getPdfWriter(), new Rectangle(30, 650, 550, 750), "txtTest");
    //textField.setText(text);
    pdfAcroForm.addFormField(pdfFormField);
    // line 7
    PdfTextArray array = new PdfTextArray("A");
    array.add(120);
    array.add("W");
    array.add(120);
    array.add("A");
    array.add(95);
    array.add("Y again");
    canvas.showText(array);
    canvas.endText();

    canvas.setColorFill(BaseColor.BLUE);
    canvas.beginText();
    canvas.setTextMatrix(360, 770);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 730);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 690);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 650);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    PdfTemplate template = canvas.createTemplate(200, 36);
    template.setLineWidth(2);
    for (int i = 0; i < 6; i++) {
        template.moveTo(0, i * 6);
        template.lineTo(200, i * 6);
    }
    template.stroke();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 610);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 610);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 570);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 570);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 530);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 530);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 490);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 490);
    canvas.restoreState();

    // step 5
    //document.add((Element) pdfAcroForm);
    document.close();
}

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

public String createInvoicePDF(String imagePath, String OUTPUT_FILEPATH)
        throws FileNotFoundException, IOException, DocumentException, InterruptedException, URISyntaxException {

    float currPosition = 0;
    String sFilepath = OUTPUT_FILEPATH;
    Image image = Image.getInstance(imagePath);
    //create a paragraph
    Paragraph paragraph = new Paragraph();
    Document d = new Document(PageSize.A4_LANDSCAPE.rotate());
    PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath));
    d.open();// w w  w.jav a  2 s  .co m
    PdfContentByte cb = w.getDirectContent();
    ByteArrayOutputStream stampedBuffer;
    URL resource = this.getClass().getClassLoader().getResource(ShippingConstants.INVOICE_TEMPLATE);
    File file = new File(resource.toURI());
    PdfReader templateReader = new PdfReader(new FileInputStream(file));
    stampedBuffer = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer);
    stamper.setFormFlattening(true);
    AcroFields form = stamper.getAcroFields();
    float[] columnWidths = { 1f, 1f, 1f, 3f };
    //create PDF table with the given widths
    PdfPTable table = new PdfPTable(columnWidths);
    // form.setField("field1", String.format("Form Text %d", i+1));
    form.setField("OBName", "Ragav");
    form.setField("OBCompany", "Ragav");
    form.setField("OBAddress", "2002 SW Sarazen Cr");
    form.setField("OBCity", "Bentonville");
    form.setField("OBPhone", "1234567890");
    form.setField("STName", "Ragav");
    form.setField("STCompany", "Ragav");
    form.setField("STAddress", "2002 SW Sarazen Cr");
    form.setField("STCity", "Bentonville");
    form.setField("STPhone", "1234567890");
    form.setField("itemNo", "12334535");
    form.setField("itemDesc", "Laundry Bag");
    stamper.close();
    templateReader.close();
    form = null;
    stamper.close();
    templateReader.close();
    PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray());
    PdfImportedPage page = w.getImportedPage(stampedReader, 1);
    cb.addTemplate(page, 0, currPosition);
    image.scaleAbsoluteHeight(325);
    image.scaleAbsoluteWidth(550);
    image.setRotationDegrees(270);
    image.setAbsolutePosition(450, 20);
    d.add(image);
    d.close();
    w.close();

    return sFilepath;
}

From source file:com.dandymadeproductions.ajqvue.io.PDFDataTableDumpThread.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb;
    String text;/* w w  w .  j av  a2 s . com*/
    float textSize;
    float textBase;
    float adjust;

    cb = writer.getDirectContent();
    textBase = document.bottom() - 20;

    cb.beginText();
    cb.setFontAndSize(BASE_FONT, 12);
    adjust = BASE_FONT.getWidthPoint("000", 12);

    cb.setTextMatrix(document.bottom(), textBase);
    cb.showText("Produced by iTextpdf");

    text = "Page " + writer.getPageNumber() + " of ";
    textSize = BASE_FONT.getWidthPoint(text, 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);

    cb.endText();

    if (pdfTemplate != null)
        cb.addTemplate(pdfTemplate, document.right() - adjust, textBase);
}

From source file:com.dandymadeproductions.myjsqlview.io.PDFDataTableDumpThread.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = BASE_FONT.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();/*w  ww. j  av  a 2  s  .  c  om*/
    cb.setFontAndSize(BASE_FONT, 12);
    float adjust = BASE_FONT.getWidthPoint("000", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(pdfTemplate, document.right() - adjust, textBase);
}

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

License:Apache License

/**
 * Creates PDf file.//  w  w  w. j  a v a 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.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * The <code>getSelectedPdfFile</code> method is used to limit the file
 * to the page limit given.//from   ww w . ja  va 2  s.c o  m
 * 
 * @param pdfFile {@link File} pdf file from which limit has to be applied
 * @param pageLimit int
 * @throws IOException if file is not found
 * @throws DocumentException if document cannot be created
 */
public static void getSelectedPdfFile(final File pdfFile, final int pageLimit)
        throws IOException, DocumentException {
    PdfReader reader = null;
    Document document = null;
    PdfContentByte contentByte = null;
    PdfWriter writer = null;
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    File newFile = null;
    if (null != pdfFile && pdfFile.exists()) {
        try {
            document = new Document();
            fileInputStream = new FileInputStream(pdfFile);

            String name = pdfFile.getName();
            final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT);
            name = name.substring(0, indexOf);
            final String finalPath = pdfFile.getParent() + File.separator + name + System.currentTimeMillis()
                    + IUtilCommonConstants.EXTENSION_PDF;
            newFile = new File(finalPath);
            fileOutputStream = new FileOutputStream(finalPath);
            writer = PdfWriter.getInstance(document, fileOutputStream);
            document.open();
            contentByte = writer.getDirectContent();

            reader = new PdfReader(fileInputStream);
            for (int i = 1; i <= pageLimit; i++) {
                document.newPage();

                // import the page from source pdf
                final PdfImportedPage page = writer.getImportedPage(reader, i);

                // add the page to the destination pdf
                contentByte.addTemplate(page, 0, 0);
                page.closePath();
            }
        } finally {
            closePassedStream(reader, document, contentByte, writer, fileInputStream, fileOutputStream);
        }
        if (pdfFile.delete() && null != newFile) {
            newFile.renameTo(pdfFile);
        } else {
            if (null != newFile) {
                newFile.delete();
            }
        }
    }
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addPdf(final File file, final Document document, final PdfWriter writer) throws Exception {
    PdfReader pdfReader = null;//from  w  w w. j a  v  a 2  s.  c  o  m
    try (InputStream is = new FileInputStream(file)) {
        pdfReader = new PdfReader(is);
        PdfContentByte cb = writer.getDirectContent();
        for (int currentPage = 1; currentPage <= pdfReader.getNumberOfPages(); currentPage++) {
            Rectangle currentPageSize = pdfReader.getPageSize(currentPage);
            document.setPageSize(currentPageSize);
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(pdfReader, currentPage);
            cb.addTemplate(page, 0, 0);
            writePageNumber(cb);

        }
        writer.flush();
    } finally {
        if (pdfReader != null) {
            writer.freeReader(pdfReader);
            ItextUtils.close(pdfReader);
        }
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void CreateTablePDF(JTable tabla) {
    boolean shapes = false;
    Document document = new Document();
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));
    File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
    if (!Dir.exists()) {
        Dir.mkdirs();/*from  w ww . j a  v  a2  s.  c  om*/
    }
    try {
        PdfWriter writer;
        if (shapes) {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        } else {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(500, 500);
        Graphics2D g2;
        if (shapes) {
            g2 = tp.createGraphicsShapes(500, 500);
        } else {
            g2 = tp.createGraphics(500, 500);
        }

        g2.dispose();
        cb.addTemplate(tp, 30, 300);
    } catch (Exception e) {
        Log.SaveLog(e.toString());
    }
    document.close();
}