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

The following examples show how to use com.itextpdf.text.Document#newPage() . 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: 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 3
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 4
Source File: ChangeMargins.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38057241/itextpdf-different-margin-on-specific-page">
 * itextpdf different margin on specific page
 * </a>
 * <p>
 * This test shows how to set different margins to separate pages.
 * </p> 
 */
@Test
public void testChangingMargins() throws IOException, DocumentException
{
    StringBuilder builder = new StringBuilder("test");
    for (int i = 0; i < 100; i++)
        builder.append(" test");
    String test = builder.toString();
    
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf")))
    {
        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();

        for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100)
        {
            // pdfDocument.setMargins(m, m, 100, 100);
            pdfDocument.setMargins(m, m, m, m);
            pdfDocument.newPage();
            pdfDocument.add(new Paragraph(test));
        }

        pdfDocument.close();
    }
}
 
Example 5
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createMultiUseIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    PdfImportedPage template = writer.getImportedPage(reader, 1);
    Rectangle pageSize = reader.getPageSize(1);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), (pageSize.getTop() + pageSize.getBottom()) / 2);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), pageSize.getBottom());
    document.newPage();
    writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom());
    document.close();

    return baos.toByteArray();
}
 
Example 6
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    PdfImportedPage template = writer.getImportedPage(reader, 1);
    Rectangle pageSize = reader.getPageSize(1);
    writer.getDirectContent().addTemplate(template, .7f, .7f, -.7f, .7f, 400, -200);
    document.newPage();
    writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom());
    document.close();

    return baos.toByteArray();
}
 
Example 7
Source File: BinaryTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39119776/itext-binary-transparency-bug">
 * iText binary transparency bug
 * </a>
 * <p>
 * Indeed, there is a bug in {@link Image#getInstance(Image, Color, boolean)},
 * the loop which determines whether to use a transparency array or a softmask
 * is erroneous and here falsely indicates a transparency array suffices.
 * </p>
 */
@Test
public void testBinaryTransparencyBug() throws IOException, DocumentException
{
    Document document = new Document();
    File file = new File(RESULT_FOLDER, "binary_transparency_bug.pdf");
    FileOutputStream outputStream = new FileOutputStream(file);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    addBackground(writer);
    document.add(new Paragraph("Binary transparency bug test case"));
    document.add(new Paragraph("OK: Visible image (opaque pixels are red, non opaque pixels are black)"));
    document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.red,false,null), null));
    document.newPage();

    addBackground(writer);
    document.add(new Paragraph("Suspected bug: invisible image (both opaque an non opaque pixels have the same color)"));
    document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,false,null), null));
    document.newPage();

    addBackground(writer);
    document.add(new Paragraph("Analysis: Aliasing makes the problem disappear, because this way the image is not binary transparent any more"));
    document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,true,null), null));
    document.newPage();

    addBackground(writer);
    document.add(new Paragraph("Analysis: Setting the color of the transparent pixels to anything but black makes the problem go away, too"));
    document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,false,Color.red), null));

    document.close();
}
 
Example 8
Source File: StampHeader.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
byte[] createSampleDocument() throws IOException, DocumentException
{
	try (	ByteArrayOutputStream baos = new ByteArrayOutputStream()	)
	{
		Document doc = new Document(new RectangleReadOnly(842,595));
		PdfWriter.getInstance(doc, baos);
		doc.open();
		doc.add(new Paragraph("Test Page 1"));
		doc.newPage();
		doc.add(new Paragraph("Test Page 2"));
		doc.close();
		return baos.toByteArray();
	}
}
 
Example 9
Source File: CreateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34408764/create-local-link-in-rotated-pdfpcell-in-itextsharp">
 * Create local link in rotated PdfPCell in iTextSharp
 * </a>
 * <p>
 * This is the equivalent Java code for the C# code in the question. Indeed, this code
 * also gives rise to the broken result. The cause is simple: Normally iText does not
 * touch the current transformation matrix. So the chunk link creation code assumes the
 * current user coordinate system to be the same as used for positioning annotations.
 * But in case of rotated cells iText does change the transformation matrix and
 * consequently the chunk link creation code positions the annotation at the wrong
 * location.
 * </p>
 */
@Test
public void testCreateLocalLinkInRotatedCell() throws IOException, DocumentException
{
    Document doc = new Document();
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "local-link.pdf")));
    doc.open();

    PdfPTable linkTable = new PdfPTable(2);
    PdfPCell linkCell = new PdfPCell();

    linkCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    linkCell.setRotation(90);
    linkCell.setFixedHeight(70);

    Anchor linkAnchor = new Anchor("Click here");
    linkAnchor.setReference("#target");
    Paragraph linkPara = new Paragraph();
    linkPara.add(linkAnchor);
    linkCell.addElement(linkPara);
    linkTable.addCell(linkCell);

    PdfPCell linkCell2 = new PdfPCell();
    Anchor linkAnchor2 = new Anchor("Click here 2");
    linkAnchor2.setReference("#target");
    Paragraph linkPara2 = new Paragraph();
    linkPara2.add(linkAnchor2);
    linkCell2.addElement(linkPara2);
    linkTable.addCell(linkCell2);

    linkTable.addCell(new PdfPCell(new Phrase("cell 3")));
    linkTable.addCell(new PdfPCell(new Phrase("cell 4")));
    doc.add(linkTable);

    doc.newPage();

    Anchor destAnchor = new Anchor("top");
    destAnchor.setName("target");
    PdfPTable destTable = new PdfPTable(1);
    PdfPCell destCell = new PdfPCell();
    Paragraph destPara = new Paragraph();
    destPara.add(destAnchor);
    destCell.addElement(destPara);
    destTable.addCell(destCell);
    destTable.addCell(new PdfPCell(new Phrase("cell 2")));
    destTable.addCell(new PdfPCell(new Phrase("cell 3")));
    destTable.addCell(new PdfPCell(new Phrase("cell 4")));
    doc.add(destTable);

    doc.close();
}
 
Example 10
Source File: MusicFontTest.java    From libreveris with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Printout of each MusicFont character
 */
@Test
public void textPrintout ()
        throws Exception
{
    File file = new File("data/temp/" + MusicFont.FONT_NAME + ".pdf");
    try (FileOutputStream fos = new FileOutputStream(file)) {
        Rectangle rect = new Rectangle(pageWidth, pageHeight);
        int x = xMargin; // Cell left side
        int y = yMargin; // Cell top side
        int line = 0;
        Document document = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphics(pageWidth, pageHeight);
        MusicFont musicFont = new MusicFont(64, 0);
        Font stringFont = g.getFont().deriveFont(24f);
        Font infoFont = stringFont.deriveFont(15f);
        String frm = "x:%4.1f y:%4.1f w:%4.1f h:%4.1f";

        for (int i = 0; i < 256; i++) {
            BasicSymbol symbol = new BasicSymbol(false, i);
            TextLayout layout = symbol.layout(musicFont);

            if (i > 0) {
                // Compute x,y for current cell
                x = xMargin + (cellWidth * (i % itemsPerLine));

                if (x == xMargin) {
                    line++;

                    if (line >= linesPerPage) {
                        // New page
                        g.dispose();
                        document.setPageSize(rect);
                        document.newPage();
                        cb = writer.getDirectContent();
                        g = cb.createGraphics(pageWidth, pageHeight);
                        x = xMargin;
                        y = yMargin;
                        line = 0;
                    } else {
                        y = yMargin + (line * cellHeight);
                    }
                }
            }

            // Draw axes
            g.setColor(Color.PINK);
            g.drawLine(
                    x + (cellWidth / 4),
                    y + (cellHeight / 2),
                    (x + cellWidth) - (cellWidth / 4),
                    y + (cellHeight / 2));
            g.drawLine(
                    x + (cellWidth / 2),
                    y + (cellHeight / 4),
                    x + (cellWidth / 2),
                    (y + cellHeight) - (cellHeight / 4));

            // Draw number
            g.setFont(stringFont);
            g.setColor(Color.RED);
            g.drawString(Integer.toString(i), x + 10, y + 30);

            // Draw info
            Rectangle2D r = layout.getBounds();
            String info = String.format(
                    frm,
                    r.getX(),
                    r.getY(),
                    r.getWidth(),
                    r.getHeight());
            g.setFont(infoFont);
            g.setColor(Color.GRAY);
            g.drawString(info, x + 5, (y + cellHeight) - 5);

            // Draw cell rectangle
            g.setColor(Color.BLUE);
            g.drawRect(x, y, cellWidth, cellHeight);

            // Draw symbol
            g.setColor(Color.BLACK);
            layout.draw(g, x + (cellWidth / 2), y + (cellHeight / 2));
        }

        // This is the end...
        g.dispose();
        document.close();
    }
}
 
Example 11
Source File: PptxToPDFConverter.java    From docs-to-pdf-converter with MIT License 4 votes vote down vote up
@Override
public void convert() throws Exception {
	loading();
	


	Dimension pgsize = processSlides();
	
	processing();
	
    double zoom = 2; // magnify it by 2 as typical slides are low res
    AffineTransform at = new AffineTransform();
    at.setToScale(zoom, zoom);

	
	Document document = new Document();

	PdfWriter writer = PdfWriter.getInstance(document, outStream);
	document.open();
	
	for (int i = 0; i < getNumSlides(); i++) {

		BufferedImage bufImg = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = bufImg.createGraphics();
		graphics.setTransform(at);
		//clear the drawing area
		graphics.setPaint(getSlideBGColor(i));
		graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
		try{
			drawOntoThisGraphic(i, graphics);
		} catch(Exception e){
			//Just ignore, draw what I have
		}
		
		Image image = Image.getInstance(bufImg, null);
		document.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight()));
		document.newPage();
		image.setAbsolutePosition(0, 0);
		document.add(image);
	}
	//Seems like I must close document if not output stream is not complete
	document.close();
	
	//Not sure what repercussions are there for closing a writer but just do it.
	writer.close();
	finished();
	

}
 
Example 12
Source File: DrawGradient.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39072316/itext-gradient-issue-in-landscape">
 * iText gradient issue in landscape
 * </a>
 * <p>
 * The problem is that while itext content adding functionalities <b>do</b> take the page
 * rotation into account (they translate the given coordinates so that in the rotated page
 * <em>x</em> goes right and <em>y</em> goes up and the origin is in the lower left), the
 * shading pattern definitions (which are <em>not</em> part of the page content but
 * externally defined) <b>don't</b>.
 * </p>
 * <p>
 * Thus, you have to make the shading definition rotation aware, e.g. like this.
 * </p>
 */
@Test
public void testGradientOnRotatedPage() throws FileNotFoundException, DocumentException
{
    Document doc = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "gradientProblem.pdf")));
    doc.open();
    drawSexyTriangle(writer, false);
    doc.setPageSize(PageSize.A4.rotate());
    doc.newPage();
    drawSexyTriangle(writer, true);
    doc.close();
}
 
Example 13
Source File: TableKeepTogether.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39529281/itext-table-inside-columntext-dont-keeptogether">
 * iText Table inside ColumnText don't keeptogether
 * </a>
 * <p>
 * The first two pages use code of the OP which does not work as desired.
 * The last page shows how the desired effect can be achieved.
 * </p>
 */
@Test
public void testKeepTogetherTableInColumnText() throws IOException, DocumentException
{
    File file = new File(RESULT_FOLDER, "keepTogetherTableInColumnText.pdf");
    OutputStream os = new FileOutputStream(file);

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

    document.open();

    PdfContentByte canvas = writer.getDirectContent();

    printPage1(document, canvas);

    document.newPage();

    printPage2(document, canvas);

    document.newPage();

    printPage3(document, canvas);

    document.close();
    os.close();
}
 
Example 14
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();
}