Java Code Examples for com.itextpdf.text.pdf.PdfContentByte#restoreState()

The following examples show how to use com.itextpdf.text.pdf.PdfContentByte#restoreState() . 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: Abstract2DPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
void split(PdfReader reader, int page) throws IOException {
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);

    Rectangle pageSizeToImport = reader.getPageSize(page);
    Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page);

    for (Rectangle rectangle : rectangles) {
        newPage(rectangle);
        PdfContentByte directContent = writer.getDirectContent();
        directContent.saveState();
        directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight());
        directContent.clip();
        directContent.newPath();

        writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom());

        directContent.restoreState();
    }
}
 
Example 2
Source File: PercentileCellBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
    public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];

        float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f);
        float yTransition = (position.getTop() + position.getBottom()) / 2f;
        float radius = (position.getRight() - position.getLeft()) * 0.025f;
        PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(),
                xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor);
        PdfShadingPattern shading = new PdfShadingPattern(axial);

        canvas.saveState();
        canvas.setShadingFill(shading);
        canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight());
//        canvas.clip();
        canvas.fill();
        canvas.restoreState();
    }
 
Example 3
Source File: AbstractPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
void split(PdfReader reader, int page) throws IOException {
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);
    PdfContentByte directContent = writer.getDirectContent();
    yPosition = pageSize.getTop();

    Rectangle pageSizeToImport = reader.getPageSize(page);
    float[] borderPositions = determineSplitPositions(reader, page);
    if (borderPositions == null || borderPositions.length < 2)
        return;

    for (int borderIndex = 0; borderIndex + 1 < borderPositions.length; borderIndex++) {
        float height = borderPositions[borderIndex] - borderPositions[borderIndex + 1];
        if (height <= 0)
            continue;

        directContent.saveState();
        directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height);
        directContent.clip();
        directContent.newPath();

        writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (borderPositions[borderIndex] - pageSizeToImport.getBottom()));

        directContent.restoreState();
        newPage();
    }
}
 
Example 4
Source File: MarkContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/50121297/missing-colored-area-on-pdf-using-itext-pdf">
 * Missing colored area on pdf using itext pdf
 * </a>
 * <p>
 * This test shows how to mark a whole table row without the
 * marking hiding the existing content or vice versa.
 * </p>
 */
@Test
public void test() throws IOException, DocumentException {
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-marked.pdf"))) {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(pdfReader, result);

        PdfContentByte canvas = stamper.getOverContent(1);
        canvas.saveState();
        PdfGState state = new PdfGState();
        state.setBlendMode(new PdfName("Multiply"));
        canvas.setGState(state);
        canvas.setColorFill(BaseColor.YELLOW);
        canvas.rectangle(60, 586, 477, 24);
        canvas.fill();
        canvas.restoreState();

        stamper.close();
    }
}
 
Example 5
Source File: ParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onEndPage(PdfWriter writer, Document document) {
    if (active) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(color);
        cb.rectangle(document.left(), document.bottom() - offset,
                document.right() - document.left(), startPosition - document.bottom());
        cb.fill();
        cb.restoreState();
    }
}
 
Example 6
Source File: ParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) {
    if (active) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(color);
        cb.rectangle(document.left(), paragraphPosition - offset,
                document.right() - document.left(), startPosition - paragraphPosition);
        cb.fill();
        cb.restoreState();
    }
}
 
Example 7
Source File: BinaryTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void addBackground(PdfWriter writer)
        throws BadElementException, MalformedURLException, IOException, DocumentException {
    PdfContentByte canvas = writer.getDirectContentUnder();
    canvas.saveState();
    canvas.addImage(bkgnd);
    canvas.restoreState();
}
 
Example 8
Source File: TestTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSimple() throws FileNotFoundException, DocumentException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "transparency.pdf")));
    writer.setCompressionLevel(0);
    document.open();
    PdfContentByte content = writer.getDirectContent();

    content.setRGBColorStroke(0, 255, 0);
    for (int y = 0; y <= 400; y+= 10)
    {
        content.moveTo(0, y);
        content.lineTo(500, y);
    }
    for (int x = 0; x <= 500; x+= 10)
    {
        content.moveTo(x, 0);
        content.lineTo(x, 400);
    }
    content.stroke();

    
    content.saveState();
    PdfGState state = new PdfGState();
    state.setFillOpacity(0.5f);
    content.setGState(state);
    content.setRGBColorFill(255, 0, 0);
    content.moveTo(162, 86);
    content.lineTo(162, 286);
    content.lineTo(362, 286);
    content.lineTo(362, 86);
    content.closePath();
    //content.fillStroke();
    content.fill();
    
    content.restoreState();

    document.close();
}
 
Example 9
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * pdf 用文字加水印,存在问题,如何支持中文
 * @author eko.zhan at 2018年9月2日 下午1:44:40
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithText() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	Font f = new Font(FontFamily.HELVETICA, 28);
	Phrase p = new Phrase("Xiaoi Robot", f);
	for (int i=1;i<=pageNo;i++) {
		PdfContentByte over = stamper.getOverContent(i);
		over.saveState();
		PdfGState gs1 = new PdfGState();
		gs1.setFillOpacity(0.5f);
		over.setGState(gs1);
		ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0);
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example 10
Source File: PdfVeryDenseMergeTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
void merge(PdfReader reader, PdfReaderContentParser parser, int page) throws IOException
{
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);
    PdfContentByte directContent = writer.getDirectContent();
    
    PageVerticalAnalyzer finder = parser.processContent(page, new PageVerticalAnalyzer());
    if (finder.verticalFlips.size() < 2)
        return;
    Rectangle pageSizeToImport = reader.getPageSize(page);

    int startFlip = finder.verticalFlips.size() - 1;
    boolean first = true;
    while (startFlip > 0)
    {
        if (!first)
            newPage();

        float freeSpace = yPosition - pageSize.getBottom(bottomMargin);
        int endFlip = startFlip + 1;
        while ((endFlip > 1) && (finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip - 2) < freeSpace))
            endFlip -=2;
        if (endFlip < startFlip)
        {
            float height = finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip);

            directContent.saveState();
            directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height);
            directContent.clip();
            directContent.newPath();

            writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (finder.verticalFlips.get(startFlip) - pageSizeToImport.getBottom()));

            directContent.restoreState();
            yPosition -= height + gap;
            startFlip = endFlip - 1;
        }
        else if (!first) 
            throw new IllegalArgumentException(String.format("Page %s content sections too large.", page));
        first = false;
    }
}
 
Example 11
Source File: TestTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testComplex() throws FileNotFoundException, DocumentException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "transparencyComplex.pdf")));
    writer.setCompressionLevel(0);
    document.open();
    PdfContentByte content = writer.getDirectContent();

    content.setRGBColorStroke(0, 255, 0);
    for (int y = 0; y <= 400; y+= 10)
    {
        content.moveTo(0, y);
        content.lineTo(500, y);
    }
    for (int x = 0; x <= 500; x+= 10)
    {
        content.moveTo(x, 0);
        content.lineTo(x, 400);
    }
    content.stroke();

    PdfTemplate template = content.createTemplate(500, 400);
    PdfTransparencyGroup group = new PdfTransparencyGroup();
    group.put(PdfName.CS, PdfName.DEVICEGRAY);
    group.setIsolated(false);
    group.setKnockout(false);
    template.setGroup(group);
    PdfShading radial = PdfShading.simpleRadial(writer, 262, 186, 10, 262, 186, 190, BaseColor.WHITE, BaseColor.BLACK, true, true);
    template.paintShading(radial);

    PdfDictionary mask = new PdfDictionary();
    mask.put(PdfName.TYPE, PdfName.MASK);
    mask.put(PdfName.S, new PdfName("Luminosity"));
    mask.put(new PdfName("G"), template.getIndirectReference());

    content.saveState();
    PdfGState state = new PdfGState();
    state.put(PdfName.SMASK, mask);
    content.setGState(state);
    content.setRGBColorFill(255, 0, 0);
    content.moveTo(162, 86);
    content.lineTo(162, 286);
    content.lineTo(362, 286);
    content.lineTo(362, 86);
    content.closePath();
    //content.fillStroke();
    content.fill();
    
    content.restoreState();

    document.close();
}
 
Example 12
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
/**
 * pdf 用图片加水印
 * @author eko.zhan at 2018年9月2日 下午1:44:58
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	final String IMG = "D:\\Xiaoi\\logo\\logo.png";
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	// text watermark
	Font f = new Font(FontFamily.HELVETICA, 30);
	Phrase p = new Phrase("Xiaoi Robot Image", f);
	// image watermark
	Image img = Image.getInstance(IMG);
	float w = img.getScaledWidth();
	float h = img.getScaledHeight();
	// transparency
	PdfGState gs1 = new PdfGState();
	gs1.setFillOpacity(0.5f);
	// properties
	PdfContentByte over;
	Rectangle pagesize;
	float x, y;
	// loop over every page
	for (int i = 1; i <= pageNo; i++) {
		pagesize = reader.getPageSizeWithRotation(i);
		x = (pagesize.getLeft() + pagesize.getRight()) / 2;
		y = (pagesize.getTop() + pagesize.getBottom()) / 2;
		over = stamper.getOverContent(i);
		over.saveState();
		over.setGState(gs1);
		if (i % 2 == 1)
			ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
		else
			over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
		over.restoreState();
	}
	stamper.close();
	reader.close();
}