Example usage for com.itextpdf.text.pdf PdfWriter getDirectContent

List of usage examples for com.itextpdf.text.pdf PdfWriter getDirectContent

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter getDirectContent.

Prototype


public PdfContentByte getDirectContent() 

Source Link

Document

Use this method to get the direct content for this document.

Usage

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }//from w ww. j  a v  a  2s . c  o m
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

/**
 * Print page numbers on right bottom corner
 * @param writer/*w w w  .j av  a  2s  .co  m*/
 * @param document
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    String text = String.format("Page %d of ", writer.getPageNumber());
    float textSize = BASE_FONT.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    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:de.beimax.talenttree.PDFGenerator.java

License:Open Source License

public void generate() throws Exception {
    // create PDF
    Document document = new Document(pageSizeValue, marginHorizontal, marginHorizontal, marginVertical,
            marginVertical);//ww w .  ja v a2  s  .  c o m
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(getFileName()));
    document.open();

    document.addAuthor("Maximilian Kalus");
    document.addCreator(
            "Star Wars Talent Tree Generator, see https://github.com/mkalus/sw-talenttree-generator");
    document.addTitle(strings.getProperty("PDFTitle", "Star Wars Talent Trees"));

    // iterate data files to generate PDF
    for (Object o : this.data) {
        Map data = (Map) o; // to map
        // check type
        String type = (String) data.get("type");
        if (type == null)
            throw new Exception("The following data contained no type: " + o.toString());
        // try to load class and create instance
        AbstractPageGenerator abstractPageGenerator;
        try {
            Class c = Class.forName(type);
            abstractPageGenerator = (AbstractPageGenerator) c.newInstance();
            if (abstractPageGenerator == null)
                throw new Exception();
        } catch (Exception e) {
            throw new Exception("Type " + type + " not valid in following data: " + o.toString());
        }

        // new page, if needed
        document.newPage();
        PdfContentByte canvas = writer.getDirectContent();

        // fill data
        abstractPageGenerator.setGenerator(this);
        abstractPageGenerator.setDocument(document);
        abstractPageGenerator.setWriter(writer);
        abstractPageGenerator.setCanvas(canvas);
        abstractPageGenerator.setData(data);

        // generate page
        abstractPageGenerator.generate();
    }

    // close and write document
    document.close();
}

From source file:de.bfs.radon.omsimulation.gui.data.OMExports.java

License:Open Source License

/**
 * //  www. j  a  v  a  2  s . c o m
 * Method to export charts as PDF files using the defined path.
 * 
 * @param path
 *          The filename and absolute path.
 * @param chart
 *          The JFreeChart object.
 * @param width
 *          The width of the PDF file.
 * @param height
 *          The height of the PDF file.
 * @param mapper
 *          The font mapper for the PDF file.
 * @param title
 *          The title of the PDF file.
 * @throws IOException
 *           If writing a PDF file fails.
 */
@SuppressWarnings("deprecation")
public static void exportPdf(String path, JFreeChart chart, int width, int height, FontMapper mapper,
        String title) throws IOException {
    File file = new File(path);
    FileOutputStream pdfStream = new FileOutputStream(file);
    BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream);
    Rectangle pagesize = new Rectangle(width, height);
    Document document = new Document();
    document.setPageSize(pagesize);
    document.setMargins(50, 50, 50, 50);
    document.addAuthor("OMSimulationTool");
    document.addSubject(title);
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput);
        document.open();
        PdfContentByte contentByte = pdfWriter.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D g2D = template.createGraphics(width, height, mapper);
        Double r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2D, r2D);
        g2D.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, "Failed to write PDF document.\n" + de.getMessage(), "Failed",
                JOptionPane.ERROR_MESSAGE);
        de.printStackTrace();
    }
    document.close();
}

From source file:de.domjos.schooltools.core.utils.fileUtils.PDFBuilder.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {//from w  ww  .ja v a 2s  . co  m
        Rectangle rect = writer.getBoxSize("art");
        Image img = Image.getInstance(Converter.convertDrawableToByteArray(this.context, R.drawable.icon));
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(img, 0, 0));
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, phrase, rect.getLeft(),
                rect.getBottom(), 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                new Phrase(String
                        .valueOf(this.context.getString(R.string.api_page) + " " + document.getPageNumber())),
                rect.getRight(), rect.getBottom(), 0);
    } catch (Exception ex) {
        Helper.printException(context, ex);
    }
}

From source file:de.fau.amos.ChartToPDF.java

License:Open Source License

/**
 * Converts Chart into PDF//w  w w .j  a va 2 s  . co  m
 * 
 * @param chart JFreeChart from CharRenderer that will be displayed in the PDF file
 * @param fileName Name of created PDF-file
 */
public void convertChart(JFreeChart chart, String fileName) {
    if (chart != null) {

        //set page size
        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight();

        //creating a new pdf document
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(new File(System.getProperty("userdir.location"), fileName + ".pdf")));
        } catch (DocumentException e) {
            e.printStackTrace();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        document.addAuthor("Green Energy Cockpit");
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        //sets the pdf page
        Graphics2D g2D = new PdfGraphics2D(tp, width, height);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);

        //draws the passed JFreeChart into the PDF file
        chart.draw(g2D, r2D);

        g2D.dispose();
        cb.addTemplate(tp, 0, 0);

        document.close();

        writer.flush();
        writer.close();
    }
}

From source file:de.fub.maps.project.snapshot.impl.PdfSnapShotExporter.java

License:Apache License

private void handleExport(final File selectedFile, final Component component) {
    RequestProcessor.getDefault().post(new Runnable() {
        @Override/* ww  w  .  j a  v a2s  . co  m*/
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {

                    if (component != null) {
                        PdfGraphics2D pdfGraphics2D = null;
                        try {
                            Dimension preferredSize = component.getSize();
                            Dimension dimension = preferredSize; //DimensionUtil.computeToA4Pdf(preferredSize);
                            // step 1
                            Document document = new Document(new Rectangle(dimension.width, dimension.height));
                            // step 2
                            PdfWriter writer = PdfWriter.getInstance(document,
                                    new FileOutputStream(selectedFile));
                            // step 3
                            document.open();
                            //                                document.newPage();
                            // step 4
                            PdfContentByte cb = writer.getDirectContent();
                            //                                PdfTemplate map = cb.createTemplate(dimension.width * 10, dimension.height * 10);
                            pdfGraphics2D = new PdfGraphics2D(cb, dimension.width, dimension.height);
                            //                                component.setPreferredSize(dimension);
                            //                                component.setSize(dimension);
                            //                                component.revalidate();
                            //                                component.repaint();
                            // paintAll must be called, a simple paint does
                            //not change the size of the component
                            component.printAll(pdfGraphics2D);
                            //                                component.setPreferredSize(preferredSize);
                            //                                component.setSize(preferredSize);
                            //                                component.revalidate();
                            //                                component.repaint();

                            pdfGraphics2D.dispose();
                            //                                cb.addTemplate(map, 0, 0);
                            // step 5
                            document.close();
                        } catch (FileNotFoundException ex) {
                            Exceptions.printStackTrace(ex);
                        } catch (DocumentException ex) {
                            Exceptions.printStackTrace(ex);
                        } finally {
                            if (pdfGraphics2D != null) {
                                pdfGraphics2D.dispose();
                            }
                        }
                    }
                }
            });
        }
    });
}

From source file:de.jost_net.JVerein.io.HeaderFooter.java

License:Open Source License

/**
 * Adds the header and the footer.//from   ww w  .  ja  va 2  s.co  m
 * 
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = document.getPageSize();
    switch (writer.getPageNumber() % 2) {
    case 0:
        // ColumnText.showTextAligned(writer.getDirectContent(),
        // Element.ALIGN_RIGHT, header[0], rect.getRight(), rect.getTop(), 0);
        break;
    case 1:
        // ColumnText.showTextAligned(writer.getDirectContent(),
        // Element.ALIGN_LEFT,
        // header[1], rect.getLeft(), rect.getTop(), 0);
        break;
    }
    float left = rect.getLeft() + document.leftMargin();
    float right = rect.getRight() - document.rightMargin();
    float bottom = rect.getBottom() + document.bottomMargin();
    PdfContentByte pc = writer.getDirectContent();
    pc.setColorStroke(BaseColor.BLACK);
    pc.setLineWidth(0.5f);
    pc.moveTo(left, bottom - 5);
    pc.lineTo(right, bottom - 5);
    pc.stroke();
    pc.moveTo(left, bottom - 25);
    pc.lineTo(right, bottom - 25);
    pc.stroke();

    ColumnText.showTextAligned(pc, Element.ALIGN_CENTER,
            new Phrase(footer + " " + pagenumber, Reporter.getFreeSans(7)), (left + right) / 2, bottom - 18, 0);
}

From source file:de.mat.utils.pdftools.PdfResize.java

License:Mozilla Public License

/**
/**//from ww  w. j  a  va2s. com
 * <h4>FeatureDomain:</h4>
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     scales and move comntents of the pdf pages from fileSrc and output to
 *     fileNew
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>create PDF - fileNew
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param fileSrc - source-pdf
 * @param fileNew - scaled dest-pdf
 * @param factorX - scaling x
 * @param factorY - scaling y
 * @param pixelLeft - move right
 * @param pixelTop - move down
 * @throws Exception
 */
public static void resizePdf(String fileSrc, String fileNew, float factorX, float factorY, float pixelLeft,
        float pixelTop) throws Exception {

    // open reader
    PdfReader reader = new PdfReader(fileSrc);

    // get pagebasedata
    int pageCount = reader.getNumberOfPages();
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getHeight();
    float height = psize.getWidth();

    // open writer
    Document documentNew = new Document(new Rectangle(height * factorY, width * factorX));
    PdfWriter writerNew = PdfWriter.getInstance(documentNew, new FileOutputStream(fileNew));
    documentNew.open();
    PdfContentByte cb = writerNew.getDirectContent();

    // iterate pages
    int i = 0;
    while (i < pageCount) {
        i++;
        // imoport page from reader and scale it to writer
        documentNew.newPage();
        PdfImportedPage page = writerNew.getImportedPage(reader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, pixelLeft, pixelTop);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("AddPage " + i + " from:" + fileSrc + " to:" + fileNew);
    }

    documentNew.close();
    writerNew.close();
}

From source file:direccion.GeneradorFormato.java

@Override
public void onEndPage(PdfWriter writer, Document document) {

    Rectangle rect = writer.getBoxSize("art");
    Image imghead = null;/*from  w  w  w  . j  a v a  2  s. c  o m*/
    PdfContentByte cbhead = null;

    //        try {
    //            imghead = Image.getInstance("LogoSapito5.png");
    //            imghead.setAbsolutePosition(0, 0);
    //            imghead.setAlignment(Image.ALIGN_CENTER);
    //            imghead.scalePercent(10f);
    //            cbhead = writer.getDirectContent();
    //            PdfTemplate tp = cbhead.createTemplate(100, 150);
    //            tp.addImage(imghead);
    //            cbhead.addTemplate(tp, 100, 715);
    //        } catch (BadElementException e) {
    //            e.printStackTrace();
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        } catch (DocumentException e) {
    //            e.printStackTrace();
    //        }

    Phrase headPhraseImg = new Phrase(cbhead + "",
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));

    Calendar c1 = Calendar.getInstance();
    Calendar c2 = new GregorianCalendar();
    String dia, mes, annio;
    dia = Integer.toString(c1.get(Calendar.DATE));
    mes = Integer.toString(c1.get(Calendar.MONTH));
    annio = Integer.toString(c1.get(Calendar.YEAR));
    Date fecha = new Date();
    String fechis = dia + "/" + mes + "/" + annio;

    Paragraph parrafo5 = new Paragraph(fechis,
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK));
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo5),
            rect.getRight(450), rect.getTop(-80), 0);

    Paragraph parrafo7 = new Paragraph("Empresa Sapito S.A. de C.V.",
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, BaseColor.BLACK));
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo7),
            rect.getBottom(250), rect.getTop(-60), 0);

    Paragraph parrafo8 = new Paragraph("Reporte algoooooo",
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD, BaseColor.BLACK));
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo8),
            rect.getBottom(250), rect.getTop(-40), 0);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_BOTTOM, new Phrase(
            "      _____________________________________________________________________________________    "),
            rect.getBorder(), rect.getTop(650), 0);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_BOTTOM, new Phrase(
            "      _____________________________________________________________________________________    "),
            rect.getBorder(), rect.getTop(-24), 0);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_BOTTOM, new Phrase(
            "      _____________________________________________________________________________________    "),
            rect.getBorder(), rect.getTop(-20), 0);

    Paragraph parrafo6 = new Paragraph(String.format("Pg %d", writer.getPageNumber()),
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK));
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo6),
            rect.getRight(-35), rect.getTop(-80), 0);
}