Java Code Examples for com.itextpdf.text.Document#close()

The following examples show how to use com.itextpdf.text.Document#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 8 votes vote down vote up
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    float y = writer.getPageSize().getTop();
    for (int i = 0; i < count; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        if (y <= pageSize.getBottom() + 2*radius)
        {
            y = pageSize.getTop();
            writer.getDirectContent().fillStroke();
            document.newPage();
        }
        writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius);
        y-= 2*radius + gap;
    }
    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example 2
Source File: AnnotationIcons.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46204693/cant-get-itext-rectangle-to-work-correctly-with-annotations">
 * Can't get itext Rectangle to work correctly with annotations
 * </a>
 * <p>
 * This test looks at a <b>Text</b> annotation added via a {@link Chunk}
 * as done by the OP. As this way of adding annotations resets the
 * annotation <b>Rect</b> to the bounding box of the rendered {@link Chunk},
 * it is not really what the OP wants.
 * </p>
 */
@Test
public void testAnnotationIconForTYD() throws FileNotFoundException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "annotationIcons.pdf")));
    document.open();

    // Not "new Rectangle(164, 190, 164, 110)" which would be empty
    Rectangle rect = new Rectangle(164, 190, 328, 300);

    // Annotation added like the OP does
    Chunk chunk_text = new Chunk("Let's test a Text annotation...");
    chunk_text.setAnnotation(PdfAnnotation.createText(writer, rect, "Warning", "This is a Text annotation with Comment icon.", false, "Comment"));        

    document.add(chunk_text);

    // Annotation added to the document without Chunk
    writer.addAnnotation(PdfAnnotation.createText(writer, rect, "Warning 2", "This is another Text annotation with Comment icon.", false, "Comment"));

    document.close();
}
 
Example 3
Source File: PDF2HTMLExample.java    From tutorials with MIT License 7 votes vote down vote up
private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException {
	Document document = new Document();
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf"));
	document.open();
	XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename));
	document.close();
}
 
Example 4
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 1; i < 20; i++)
    {
        Paragraph paragraph = new Paragraph();
        for (int j = 0; j < i; j++)
            paragraph.add("Hello World! ");
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 5
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
void run(IGanttProject project, UIFacade facade, OutputStream out) throws ExportException {
  myProject = project;
  myUIFacade = facade;
  Rectangle pageSize = PageSize.getRectangle(myPageSizeOption.getValue());
  if (myLandscapeOption.isChecked()) {
    pageSize = pageSize.rotate();
  }
  myDoc = new Document(pageSize, 20, 20, 70, 40);
  try {
    myWriter = PdfWriter.getInstance(myDoc, out);
    myWriter.setPageEvent(this);
    myDoc.open();
    writeProject();
  } catch (Throwable e) {
    e.printStackTrace();
    throw new ExportException("Export failed", e);
  } finally {
    myDoc.close();
  }
}
 
Example 6
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleCircleGraphicsPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    float y = writer.getPageSize().getTop(document.topMargin());
    float radius = 20;
    for (int i = 0; i < 3; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        writer.getDirectContent().circle(
                pageSize.getLeft(document.leftMargin()) + (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) * Math.random(),
                y-radius, radius);
        y-= 2*radius + 5;
    }

    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example 7
Source File: DoubleSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf">
 * Double space not being preserved in PDF
 * </a>
 * <p>
 * Indeed, the double space collapses into a single one when copying&pasting from the
 * generated PDF displayed in Adobe Reader. On the other hand the gap for the double
 * space is twice as wide as for the single space. So this essentially is a quirk of
 * copy&paste of Adobe Reader (and some other PDF viewers, too).
 * </p>
 */
@Test
public void testDoubleSpace() throws DocumentException, IOException
{
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf")))
    {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorderWidth(0.5f);
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();
        pdfDocument.add(table);
        pdfDocument.close();
    }
}
 
Example 8
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines">
 * iTextSharp: Extra space between lines
 * </a>
 * <p>
 * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored.
 * The reason is that the op is working in text mode. Thus, he has to use
 * {@link ColumnText#setLeading(float, float)} instead, cf.
 * {@link #testLikeUser3208131Fixed()}.
 * </p>
 */
@Test
public void testLikeUser3208131() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131.pdf")));
    document.open();

    Font font = new Font(FontFamily.UNDEFINED, 4, Font.UNDEFINED, null);
    PdfContentByte cb = writer.getDirectContent();
    ColumnText ct = new ColumnText(cb);

    float gutter = 15;
    float colwidth = (document.getPageSize().getRight() - document.getPageSize().getLeft() - gutter) / 2;

    float[] left = { document.getPageSize().getLeft() + 133, document.getPageSize().getTop() - 35,
            document.getPageSize().getLeft() + 133, document.getPageSize().getBottom() };
    float[] right = { document.getPageSize().getLeft() + colwidth, document.getPageSize().getTop() - 35,
            document.getPageSize().getLeft() + colwidth, document.getPageSize().getBottom() };

    for (int i = 0; i < 3; i++)
    {
        Phrase Ps = new Phrase("Test " + i + "\n", font);
        Ps.setLeading(0.0f, 0.6f);
        ct.addText(Ps);
        ct.addText(Chunk.NEWLINE);
    }
    ct.setColumns(left, right);
    ct.go();

    document.close();
}
 
Example 9
Source File: MemoryConsumption.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38989235/itext-html-to-pdf-memory-leak">
 * IText HTML to PDF memory leak
 * </a>
 * <p>
 * The OP's code plus a save-to-file.
 * </p>
 */
public void testDevelofersScenario(String outputName) throws IOException, DocumentException
{
    final String content = "<!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->\n<html>\n <head>\n    <title>Title</title>\n    \n   \n </head>\n"
            + "\n    \n<body>  \n  \n      \nEXAMPLE\n\n</body>\n</html>";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);        
    document.open();
    InputStream is = new ByteArrayInputStream(content.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    document.close();
    
    baos.writeTo(new FileOutputStream(new File(RESULT_FOLDER, outputName)));
}
 
Example 10
Source File: TableWithSpan.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40947306/strange-setrowspan-error-not-working">
 * Strange setRowspan error/not working
 * </a>
 * <p>
 * Selecting 1 header row and having a cell in the first row which spans 2 rows
 * does not match. iText ignores the row span resulting in the weird appearance.
 * </p>
 */
@Test
public void testRowspanWithHeaderRows() throws IOException, DocumentException
{
    File file = new File(RESULT_FOLDER, "rowspanWithHeaderRows.pdf");
    OutputStream os = new FileOutputStream(file);

    Document document = new Document();
    /*PdfWriter writer =*/ PdfWriter.getInstance(document, os);
    document.open();

    document.add(createHeaderContent());
    document.newPage();
    document.add(createHeaderContent(new int[] {5,5,5,5,5}));

    document.close();
}
 
Example 11
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testWithWriter() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        Rectangle pageSize = reader.getPageSize(1);

        Rectangle rect = getOutputPageSize(pageSize, reader, 1);

        Document document = new Document(rect, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf")));

        document.open();
        PdfImportedPage page;

        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            System.out.println("BBox:  "+ page.getBoundingBox().toString());
            Image instance = Image.getInstance(page);
            document.add(instance);
            Rectangle outputPageSize = document.getPageSize();
            System.out.println(outputPageSize.toString());
        }
        document.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 12
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();

    BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 0, 500, -500, 0, 550, 50);

    document.close();

    return baos.toByteArray();
}
 
Example 13
Source File: ChartExportUtil.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method saves a chart as a PDF with given dimensions
 *
 * @param chart
 * @param width
 * @param height
 * @param fileName is a full path
 */
public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName)
    throws Exception {
  PdfWriter writer = null;

  Document document = new Document(new Rectangle(width, height));

  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
    Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);

    chart.draw(graphics2d, rectangle2d);

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

  } catch (Exception e) {
    e.printStackTrace();
    throw e;
  } finally {
    document.close();
  }
}
 
Example 14
Source File: SplitIntoHalfPages.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This methods creates a copy of the source document containing each page twice,
 * once with the cropbox limited to the left half page, once to the right one.
 */
void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException
{
    final PdfReader reader = new PdfReader(source);
    
    try (   OutputStream targetStream = new FileOutputStream(target)    )
    {
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, targetStream);
        document.open();

        for (int page = 1; page <= reader.getNumberOfPages(); page++)
        {
            PdfDictionary pageN = reader.getPageN(page);
            Rectangle cropBox = reader.getCropBox(page);
            PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()});
            PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()});

            PdfImportedPage importedPage = copy.getImportedPage(reader, page);
            pageN.put(PdfName.CROPBOX, leftBox);
            copy.addPage(importedPage);
            pageN.put(PdfName.CROPBOX, rightBox);
            copy.addPage(importedPage);
        }
        
        document.close();
    }
    finally
    {
        reader.close();
    }
}
 
Example 15
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
 * Creating table in pdf on last page bottom (wrong official solution)
 * </a>
 * <p>
 * Indeed, there is an error in the official sample which effectively
 * applies the margins twice.
 * </p>
 */
@Test
public void testCreateTableLikeUser7968180() throws FileNotFoundException, DocumentException
{
    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(new File(RESULT_FOLDER, "calendarUser7968180.pdf")));
    document.open();

    PdfPTable datatable = null;//createHeaderTable();
    //document.add(datatable);
    datatable = createFooterTable();

    drawTableAtTheEndOfPage(document, writer, datatable);

    // Marking the border
    PdfContentByte canvas = writer.getDirectContentUnder();
    canvas.setColorStroke(BaseColor.RED);
    canvas.setColorFill(BaseColor.PINK);
    canvas.rectangle(document.left(), document.bottom(), document.right() - document.left(), document.top() - document.bottom());
    Rectangle pageSize = document.getPageSize(); 
    canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
    canvas.eoFillStroke();

    document.close();
    System.out.println("done");
}
 
Example 16
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31980979/itext-importing-styled-text-and-informations-from-an-existing-pdf">
 * iText: Importing styled Text and informations from an existing PDF
 * </a>
 * <p>
 * This method demonstrates how to import merely the region of a PDF page with
 * actual content. The main necessity is to call {@link #cropPdf(PdfReader)}
 * for the reader in question which restricts the media boxes of the pages to
 * the bounding box of the existing content.
 * </p>
 */
@Test
public void testImportPages() throws DocumentException, IOException
{
    byte[] docText = createSimpleTextPdf();
    Files.write(new File(RESULT_FOLDER, "textOnly.pdf").toPath(), docText);
    byte[] docGraphics = createSimpleCircleGraphicsPdf();
    Files.write(new File(RESULT_FOLDER, "graphicsOnly.pdf").toPath(), docGraphics);

    PdfReader readerText = new PdfReader(docText);
    cropPdf(readerText);
    PdfReader readerGraphics = new PdfReader(docGraphics);
    cropPdf(readerGraphics);
    try (   FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "importPages.pdf")))
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();
        document.add(new Paragraph("Let's import 'textOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerText, 1)));
        document.add(new Paragraph("and now 'graphicsOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerGraphics, 1)));
        document.add(new Paragraph("That's all, folks!", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));

        document.close();
    }
    finally
    {
        readerText.close();
        readerGraphics.close();
    }
}
 
Example 17
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * The original code used by the OP. This code adds the second cell
 * with rowspan 2 too early. Fixed in {@link #createPdfFixed(String)}.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #addCellToTableCzech(PdfPTable, int, int, String, int, int, String, float)
 */
public void createPdf(String dest) throws IOException, DocumentException {
    int horizontalAlignmentCenter = Element.ALIGN_CENTER;
    int verticalAlignmentMiddle = Element.ALIGN_MIDDLE;
    String fontTypeRegular = "c:/Windows/Fonts/arial.ttf";
    float fontSizeRegular = 10f;

    float[] columns = { 100, 50, 100, 50, 50, 50, 50, 50, 75, 50, 50, 50 };
    int numberOfColumns = columns.length;
    Document document = new Document(PageSize.A4.rotate(), 36, 36, 36, 36);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    PdfPTable subTableZkouska = new PdfPTable(numberOfColumns);
    subTableZkouska.setTotalWidth(columns);
    subTableZkouska.setLockedWidth(true);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "Brno �pit�lka 8 Brno H�jeck� 1068/14 CZ5159", 1,
            2, fontTypeRegular, fontSizeRegular);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 2, fontTypeRegular, fontSizeRegular);

    for (int i = 0; i < 19; i++) {
        addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
                verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular,
                fontSizeRegular);
    }
    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular, fontSizeRegular);

    document.add(subTableZkouska);
    document.close();
}
 
Example 18
Source File: DocumentCropper.java    From Briss-2.0 with GNU General Public License v3.0 4 votes vote down vote up
private static File copyToMultiplePages(final CropDefinition cropDefinition,
                                        final PdfMetaInformation pdfMetaInformation) throws IOException, DocumentException {

    PdfReader reader = new PdfReader(cropDefinition.getSourceFile().getAbsolutePath());
    HashMap<String, String> map = SimpleNamedDestination.getNamedDestination(reader, false);
    Document document = new Document();

    File resultFile = File.createTempFile("cropped", ".pdf");
    PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile));
    document.open();

    Map<Integer, List<String>> pageNrToDestinations = new HashMap<Integer, List<String>>();
    for (String single : map.keySet()) {
        StringTokenizer st = new StringTokenizer(map.get(single), " ");
        if (st.hasMoreElements()) {
            String pageNrString = (String) st.nextElement();
            int pageNr = Integer.parseInt(pageNrString);
            List<String> singleList = (pageNrToDestinations.get(pageNr));
            if (singleList == null) {
                singleList = new ArrayList<String>();
                singleList.add(single);
                pageNrToDestinations.put(pageNr, singleList);
            } else {
                singleList.add(single);
            }
        }
    }

    int outputPageNumber = 0;
    for (int pageNumber = 1; pageNumber <= pdfMetaInformation.getSourcePageCount(); pageNumber++) {

        PdfImportedPage pdfPage = pdfCopy.getImportedPage(reader, pageNumber);

        pdfCopy.addPage(pdfPage);
        outputPageNumber++;
        List<String> destinations = pageNrToDestinations.get(pageNumber);
        if (destinations != null) {
            for (String destination : destinations)
                pdfCopy.addNamedDestination(destination, outputPageNumber, new PdfDestination(PdfDestination.FIT));
        }
        List<Float[]> rectangles = cropDefinition.getRectanglesForPage(pageNumber);
        for (int j = 1; j < rectangles.size(); j++) {
            pdfCopy.addPage(pdfPage);
            outputPageNumber++;
        }
    }
    document.close();
    pdfCopy.close();
    reader.close();
    return resultFile;
}
 
Example 19
Source File: AddRotatedImage.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39364197/how-to-rotate-around-the-image-center-by-itext">
 * How to rotate around the image center by itext?
 * </a>
 * <p>
 * This test draws an image at given coordinates without rotation and then again
 * as if that image was flipped and rotated around its center by some angle.
 * </p>
 */
@Test
public void testAddRotatedFlippedImage() throws IOException, DocumentException
{
    try (   FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "rotatedFlippedImage.pdf"))    )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, stream);
        document.open();

        PdfContentByte contentByte = writer.getDirectContent();

        int x = 200;
        int y = 300;
        float rotate = (float) Math.PI / 3;

        try (InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/itext5/layer/Willi-1.jpg"))
        {
            Image image = Image.getInstance(IOUtils.toByteArray(imageStream));

            // Draw image at x,y without rotation
            contentByte.addImage(image, image.getWidth(), 0, 0, image.getHeight(), x, y);

            // Draw image as if the previous image was flipped and rotated around its center
            // Image starts out being 1x1 with origin in lower left
            // Move origin to center of image
            AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5);
            // Flip it horizontally
            AffineTransform B = new AffineTransform(-1, 0, 0, 1, 0, 0);
            // Stretch it to its dimensions
            AffineTransform C = AffineTransform.getScaleInstance(image.getWidth(), image.getHeight());
            // Rotate it
            AffineTransform D = AffineTransform.getRotateInstance(rotate);
            // Move it to have the same center as above
            AffineTransform E = AffineTransform.getTranslateInstance(x + image.getWidth()/2, y + image.getHeight()/2);
            // Concatenate
            AffineTransform M = (AffineTransform) A.clone();
            M.preConcatenate(B);
            M.preConcatenate(C);
            M.preConcatenate(D);
            M.preConcatenate(E);
            //Draw
            contentByte.addImage(image, M);
        }

        document.close();
    }
}
 
Example 20
Source File: ReportFactory.java    From graylog-plugin-aggregates with GNU General Public License v3.0 2 votes vote down vote up
@SuppressWarnings("deprecation")
public static void writeChartsToPDF(List<JFreeChart> charts, int width, int height, OutputStream outputStream, String hostname, Date date) {
	PdfWriter writer = null;

	Document document = new Document();

	
	try {
		
		writer = PdfWriter.getInstance(document, outputStream);
		writer.setPageEmpty(false);
		
		
		
		document.open();
		document.setPageSize(PageSize.A4);
		document.add(new Paragraph("Aggregates Report generated by " + hostname + " on " + date.toString()));
		document.newPage();
		writer.newPage();
		
		PdfContentByte contentByte = writer.getDirectContent();
		
		PdfTemplate template;
		Graphics2D graphics2d;
		
		
		int position = 0;
		Rectangle2D rectangle2d;
		
		
		for (JFreeChart chart : charts){
			LOG.debug("Writing chart to PDF");
			if (writer.getVerticalPosition(true)-height+(height*position) < 0){
				position = 0;
				document.newPage();
				writer.newPage();					
				
			}
			template = contentByte.createTemplate(width, height);
			graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
			rectangle2d = new Rectangle2D.Double(0, 0, width, height);
			chart.draw(graphics2d, rectangle2d);
			graphics2d.dispose();

			
			contentByte.addTemplate(template, 38, writer.getVerticalPosition(true)-height+(height*position));
			position--;
			
			

		}

	} catch (Exception e) {
		e.printStackTrace();
	}
	document.close();
}