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

The following examples show how to use com.itextpdf.text.pdf.PdfContentByte#setColorFill() . 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: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 9 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 2
Source File: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example 3
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * The OP's code transformed into Java changed with the work-around.
 */
void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.setColorFill(new BaseColor(255,200,200));
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 4
Source File: HideContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer">
 * Filling a PDF with iTextsharp and then hiding the base layer
 * </a>
 * <p>
 * This test shows how to cover all content using a white rectangle.
 * </p>
 */
@Test
public void testHideContenUnderRectangle() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        for (int page = 1; page <= pdfReader.getNumberOfPages(); page++)
        {
            Rectangle pageSize = pdfReader.getPageSize(page);
            PdfContentByte canvas = pdfStamper.getOverContent(page);
            canvas.setColorFill(BaseColor.WHITE);
            canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
            canvas.fill();
        }
        pdfStamper.close();
    }
}
 
Example 5
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 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 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 7
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 8
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 9
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void enhance(PdfContentByte page, Collection<Rectangle2D> rectangles, Point2D point, BaseColor color)
{
    Rectangle2D best = null;
    double bestDist = Double.MAX_VALUE;

    for (Rectangle2D rectangle : rectangles)
    {
        double distance = distance(rectangle, point);
        if (distance < bestDist)
        {
            best = rectangle;
            bestDist = distance;
        }
    }

    if (best != null)
    {
        page.setColorFill(color);
        page.rectangle((float) best.getMinX(), (float) best.getMinY(), (float) best.getWidth(), (float) best.getHeight());
        page.fill();
        System.out.printf("    Best rectangle for %7.3f, %7.3f is %7.3f, %7.3f, %7.3f, %7.3f\n", point.getX(), point.getY(), best.getMinX(),
                best.getMinY(), best.getWidth(), best.getHeight());
    }
    else
    {
        System.err.printf("!!! No best rectangle for %7.3f, %7.3f\n", point.getX(), point.getY());
    }
}
 
Example 10
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSimplePatternPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    PdfContentByte directContent = writer.getDirectContent();
    Rectangle pageSuze = document.getPageSize();
    
    PdfPatternPainter painter = directContent.createPattern(200, 150);
    painter.setColorStroke(BaseColor.GREEN);
    painter.beginText();
    painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);
    painter.setTextMatrix(AffineTransform.getTranslateInstance(0, 50));
    painter.setFontAndSize(BaseFont.createFont(), 100);
    painter.showText("Test");
    painter.endText();

    directContent.setColorFill(new PatternColor(painter));
    directContent.rectangle(pageSuze.getLeft(), pageSuze.getBottom(), pageSuze.getWidth(), pageSuze.getHeight());
    directContent.fill();

    document.close();

    return baos.toByteArray();
}
 
Example 11
Source File: TrpPdfDocument.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
private void addTextAndImage(PcGtsType pc, int cutoffLeft, int cutoffTop, Image img, boolean imageOnly, ExportCache cache) throws DocumentException, IOException {
		lineAndColorList.clear();
		
		PdfContentByte cb = writer.getDirectContentUnder();

		cb.setColorFill(BaseColor.BLACK);
		cb.setColorStroke(BaseColor.BLACK);
		//BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, "UTF-8", BaseFont.NOT_EMBEDDED);
		if (!imageOnly){
			cb.beginLayer(ocrLayer);
			//cb.setFontAndSize(bfArial, 32);
			cb.setFontAndSize(mainExportBaseFont, 32);
					
			List<TrpRegionType> regions = pc.getPage().getTextRegionOrImageRegionOrLineDrawingRegion();
			
			/*
			 * use reading order comparator for sorting since at this time reading order is more trustable
			 * other sorting is not transitive and seldomly produces "Comparison violates its general contract" exception
			 */
//			Collections.sort(regions, new TrpElementReadingOrderComparator<RegionType>(true));
			TrpShapeTypeUtils.sortShapesByReadingOrderOrCoordinates(regions);
	
			for(RegionType r : regions){
				//TODO add paths for tables etc.
				if (r instanceof TrpTableRegionType){
					
					exportTable(r, cb, cutoffLeft, cutoffTop, false, cache);

				}
				else if(r instanceof TextRegionType){
					TextRegionType tr = (TextRegionType)r;
					//PageXmlUtils.buildPolygon(tr.getCoords().getPoints()).getBounds().getMinX();
					addTextFromTextRegion(tr, cb, cutoffLeft, cutoffTop, mainExportBaseFont, cache);
				}
			}
			
			//scale after calculating lineMeanHeightForAllRegions
			//lineMeanHeight = lineMeanHeight/scaleFactorX;
			
			cb.endLayer();
		}
				
		cb.beginLayer(imgLayer);		
		cb.addImage(img);
		cb.endLayer();
		
		if (highlightTags || highlightArticles){
			
			highlightAllTagsOnImg(lineAndColorList, cb, cutoffLeft, cutoffTop);
		}
		
		/*
		 * draw tag lines
		 */
		

		
//		addTocLinks(doc, page,cutoffTop);
	}
 
Example 12
Source File: TrpPdfDocument.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
private void addUniformText(PcGtsType pc, int cutoffLeft, int cutoffTop, ExportCache cache) throws DocumentException, IOException {
		PdfContentByte cb = writer.getDirectContentUnder();
		cb.setColorFill(BaseColor.BLACK);
		cb.setColorStroke(BaseColor.BLACK);
	    /** The path to the font. */
	    //FontFactory.register("c:/windows/fonts/arialbd.ttf");
		//BaseFont bf = BaseFont.createFont("/fonts/arialbd.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		
		cb.beginLayer(ocrLayer);
		//FontFactory.register("arialbd.ttf", "my_bold_font");
		//Font fontTest = FontFactory.getFont("arialbd.ttf", Font.BOLDITALIC);
		
		cb.setFontAndSize(mainExportBaseFont, 10);
				
		List<TrpRegionType> regions = pc.getPage().getTextRegionOrImageRegionOrLineDrawingRegion();
		
		/*
		 * use reading order comparator for sorting since at this time reading order is more trustable
		 * other sorting is not transitive and seldomly produces "Comparison violates its general contract" exception
		 */
//		Collections.sort(regions, new TrpElementReadingOrderComparator<RegionType>(true));
		TrpShapeTypeUtils.sortShapesByReadingOrderOrCoordinates(regions);
		
		float textBlockXStart = 0;

		int i = 0;
		for(TrpRegionType r : regions){
			//TODO add paths for tables etc.			
			if (r instanceof TrpTableRegionType){
				exportTable(r, cb, cutoffLeft, cutoffTop, true, cache);
			}
			else if(r instanceof TrpTextRegionType){
				TrpTextRegionType tr = (TrpTextRegionType) r;
				
				//compute average text region start
				//textBlockXStart = (float) (PageXmlUtils.buildPolygon(tr.getCoords().getPoints()).getBounds().getMinX());
				//double minX = PageXmlUtils.buildPolygon(tr.getCoords().getPoints()).getBounds().getMinX();
				//this should result in the the same value as the method in the line above which is deprecated
				double minX = tr.getBoundingBox().getMinX();
				double maxX = tr.getBoundingBox().getMaxX();
				double trWidth = tr.getBoundingBox().getWidth();
				
//				logger.debug("region "+ ++i);
//				logger.debug("region minX " + minX);
//				logger.debug("region maxX " + tr.getBoundingBox().getMaxX());

				//if there is only one text region at this vertical section start the text block at the second twelfth
				//if (hasSmallerColumn(regions, tr)){
				if (isOnlyRegionInThisRow(regions, tr)){
				//if (regions.size() == 1){
					logger.debug("only one region in this row!!");
					//indent start of text block under certain preconditions
					if (minX < twelfthPoints[1][0] && (twelfthPoints[1][0] < maxX && trWidth > twelfthPoints[2][0])){
						textBlockXStart = twelfthPoints[1][0];
					}
					//if textregion contains only one line this is probably a headline
					else if (tr.getTextLine().size() == 1){
						//logger.debug("tr.getTextLine().size() == 1 ");
						textBlockXStart = getPrintregionStartX((float) (minX), tr.getBoundingBox().getMaxX());
					}
					else if (twelfthPoints[2][0] < maxX && trWidth > twelfthPoints[3][0]){
						//logger.debug("twelfthPoints[2][0] < tr.getBoundingBox().getMaxX() ");
						textBlockXStart = twelfthPoints[2][0];
					}
					else{
						textBlockXStart = (float) minX;
					}
				}
				else{
					
					logger.debug("several columns found, minX of text region is : " + minX);
					//float startWithThisX = (float) (minX < smallerRegionMaxX ? smallerRegionMaxX : minX);
					//textBlockXStart = getPrintregionStartX((float) (startWithThisX));
					
					/*
					 * this is then used for all lines of a region as start point
					 */
					textBlockXStart = getAverageBeginningOfBaselines(tr);
					textBlockXStart += 40;

				}
				//logger.debug("textBlockXStart " + textBlockXStart);
				addUniformTextFromTextRegion(tr, cb, cutoffLeft, cutoffTop, mainExportBaseFont, textBlockXStart, cache);
			}
		}
		
		cb.endLayer();	
		
//		addTocLinks(doc, page,cutoffTop);
	}