com.itextpdf.text.BaseColor Java Examples

The following examples show how to use com.itextpdf.text.BaseColor. 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: 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 #5
Source File: DrawGradient.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void drawSexyTriangle(PdfWriter writer, boolean rotated)
{
    PdfContentByte canvas = writer.getDirectContent();
    float x = 36;
    float y = 400;
    float side = 70;
    PdfShading axial = rotated ?
            PdfShading.simpleAxial(writer, PageSize.A4.getRight() - y, x, PageSize.A4.getRight() - y, x + side, BaseColor.PINK, BaseColor.BLUE)
            : PdfShading.simpleAxial(writer, x, y, x + side, y, BaseColor.PINK, BaseColor.BLUE);
    PdfShadingPattern shading = new PdfShadingPattern(axial);
    canvas.setShadingFill(shading);
    canvas.moveTo(x,y);
    canvas.lineTo(x + side, y);
    canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3))));
    canvas.closePathFillStroke();
}
 
Example #6
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/38240692/error-in-redaction-with-itext-5-the-color-depth-1-is-not-supported-exception">
 * Error in redaction with iText 5: “The color depth 1 is not supported.” exception when apply redaction on pdf which contain image also
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVbkhQQk9tR2hpSUE/view?pref=2&pli=1">
 * Pages from Miscellaneous_corrupt.pdf
 * </a>
 * <p>
 * In iText 5.5.11 a work-around for this issue has been added to iText, images in
 * formats not explicitly supported by itext are now removed as a whole if they
 * intersect a redaction area.
 * </p>
 */
@Test
public void testRedactLikeMayankPandeyPagesfromMiscellaneous_corrupt() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Pages from Miscellaneous_corrupt.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Pages from Miscellaneous_corrupt-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfCleanUpProcessor cleaner= null;
        PdfStamper stamper = new PdfStamper(reader, result);
        stamper.setRotateContents(false);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        Rectangle rectangle = new Rectangle(190, 320, 430, 665);
        cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK));
        cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);   
        cleaner.cleanUp();
        stamper.close();
        reader.close();
    }
}
 
Example #7
Source File: UseMillimeters.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor color)
{
    float posX = Utilities.millimetersToPoints(x);
    float posY = Utilities.millimetersToPoints(y);

    float widthX = Utilities.millimetersToPoints(width + x);
    float heightY = Utilities.millimetersToPoints(height + y);

    Rectangle rectangle = new Rectangle(posX, posY, widthX, heightY);

    PdfContentByte canvas = writer.getDirectContent();
    rectangle.setBorder(Rectangle.BOX);
    rectangle.setBorderWidth(1);
    rectangle.setBorderColor(color);
    canvas.rectangle(rectangle);
}
 
Example #8
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 #9
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t">
 * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5
 * </a>
 * <p>
 * This test creates an ellipse annotation without appearance on a page with rotation.
 * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader.
 * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipseOnRotated() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90));

        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150);

        PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false);
        annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
        annotation.setColor(BaseColor.RED);
        annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID));

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #10
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridColumnHeader(PdfPTable table, Collection<ColumnHeader> topHeaders, int maxHeaderLevel) throws Exception {
	for (int i = 1; i < 50; i++) {
		List<ColumnHeader> result = new ArrayList<ColumnHeader>();
		generateGridHeadersByLevel(topHeaders, i, result);
		for (ColumnHeader header : result) {
			PdfPCell cell = new PdfPCell(createParagraph(header));
			if (header.getBgColor() != null) {
				int[] colors = header.getBgColor();
				cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
			}
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(header.getAlign());
			cell.setColspan(header.getColspan());
			if (header.getColumnHeaders().size() == 0) {
				int rowspan = maxHeaderLevel - (header.getLevel() - 1);
				if (rowspan > 0) {
					cell.setRowspan(rowspan);
				}
			}
			table.addCell(cell);
		}
	}
}
 
Example #11
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 #12
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed">
 * itextpdf Redaction :Partly redacted text string is fully removed
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view">
 * Document.pdf
 * </a>
 * <p>
 * This indeed is a case which shows that glyphs are completely removed even if their
 * bounding box merely minutely intersects the redaction area. While not desired by
 * the OP, this is how <code>PdfCleanUp</code> works.
 * </p>
 * 
 * @see #testRedactStrictForMayankPandey()
 * @see #testRedactStrictForMayankPandeyLarge()
 */
@Test
public void testRedactLikeMayankPandey() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Document.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfCleanUpProcessor cleaner= null;
        PdfStamper stamper = new PdfStamper(reader, result);
        stamper.setRotateContents(false);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        Rectangle rectangle = new Rectangle(380, 640, 430, 665);
        cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK));
        cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);   
        cleaner.cleanUp();
        stamper.close();
        reader.close();
    }
}
 
Example #13
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testOPCode() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 );
        PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT;
        PdfAnnotation linkRed  = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" );
        PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" );
        BaseColor baseColorRed = new BaseColor(255,0,0);
        BaseColor baseColorGreen = new BaseColor(0,255,0);
        linkRed.setColor(baseColorRed);
        linkGreen.setColor(baseColorGreen);
        double angleDegrees = 10;
        double angleRadians = Math.PI*angleDegrees/180;
        stamper.addAnnotation(linkRed, 1);
        linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians));
        stamper.addAnnotation(linkGreen, 1);
        stamper.close();
    }
}
 
Example #14
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public void cellLayout(PdfPCell cell, Rectangle position,
                               PdfContentByte[] canvases) {
            PdfWriter writer = canvases[0].getPdfWriter();
            float x = position.getLeft();
            float y = position.getBottom();
            Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5);
            RadioCheckField checkbox = new RadioCheckField(
                    writer, rect, name, "Yes");
            checkbox.setCheckType(RadioCheckField.TYPE_CROSS);
            checkbox.setChecked(check);
// change: set border color
            checkbox.setBorderColor(BaseColor.BLACK);

            try {
                pdfStamper.addAnnotation(checkbox.getCheckField(), page);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }
 
Example #15
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridTableDatas(PdfPTable table, Collection<ReportData> datas) {
	for (ReportData data : datas) {
		PdfPCell cell = new PdfPCell(createParagraph(data.getTextChunk()));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		int level = this.calculateIndentationCount(data.getTextChunk().getText());
		if (data.getBgColor() != null) {
			int[] colors = data.getBgColor();
			cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
		}
		if (level == 0) {
			cell.setHorizontalAlignment(data.getAlign());
		} else {
			cell.setIndent(20 * level);
		}
		table.addCell(cell);
	}
}
 
Example #16
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same
 * font and chunk as stamped by the OP. Adobe Reader has no problem with it either.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testCreateUnicodePdf() throws DocumentException, IOException
{
    Document document = new Document();
    try (   OutputStream result  = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) )
    {
        PdfWriter.getInstance(document, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        document.open();
        
        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        document.add(p);
        
        document.close();
    }
}
 
Example #17
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't as this test shows.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampEg_01() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("eg_01.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #18
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader. With a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #19
Source File: DividerAndColorAwareTextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31730278/extract-text-from-pdf-between-two-dividers-with-itextsharp">
 * Extract text from PDF between two dividers with ITextSharp
 * </a>
 * <br>
 * <a href="http://www.tjsc.jus.br/institucional/diario/a2015/20150211600.PDF">
 * 20150211600.PDF
 * </a>
 * <p>
 * This test applies the {@link DividerAndColorAwareTextExtractionStrategy} to the OP's sample
 * document, page 346, to demonstrate its use.
 * </p>
 */
@Test
public void test20150211600_346() throws IOException, DocumentException {
    InputStream resourceStream = getClass().getResourceAsStream("20150211600.PDF");
    BaseColor headerColor = new CMYKColor(0.58f, 0.17f, 0, 0.56f);
    try {
        PdfReader reader = new PdfReader(resourceStream);
        String content = extractAndStore(reader, new File(RESULT_FOLDER, "20150211600.%s.%s.txt").toString(), 346, 346, headerColor);

        System.out.println("\nText 20150211600.PDF\n************************");
        System.out.println(content);
        System.out.println("************************");
    } finally {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #20
Source File: DividerAndColorAwareTextExtractionStrategy.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method checks whether two colors are approximately equal. As the
 * sample document only uses CMYK colors, only this comparison has been
 * implemented yet.
 */
boolean approximates(BaseColor colorA, BaseColor colorB)
{
    if (colorA == null || colorB == null)
        return colorA == colorB;
    if (colorA instanceof CMYKColor && colorB instanceof CMYKColor)
    {
        CMYKColor cmykA = (CMYKColor) colorA;
        CMYKColor cmykB = (CMYKColor) colorB;
        float c = Math.abs(cmykA.getCyan() - cmykB.getCyan());
        float m = Math.abs(cmykA.getMagenta() - cmykB.getMagenta());
        float y = Math.abs(cmykA.getYellow() - cmykB.getYellow());
        float k = Math.abs(cmykA.getBlack() - cmykB.getBlack());
        return c+m+y+k < 0.01;
    }
    // TODO: Implement comparison for other color types
    return false;
}
 
Example #21
Source File: DividerAndColorAwareTextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
String extractAndStore(PdfReader reader, String format, int from, int to, BaseColor headerColor) throws IOException {
    StringBuilder builder = new StringBuilder();

    for (int page = from; page <= to; page++) {
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        DividerAwareTextExtrationStrategy strategy = parser.processContent(page, new DividerAndColorAwareTextExtractionStrategy(810, 30, 20, 575, headerColor));

        List<Section> sections = strategy.getSections();
        int i = 0;
        for (Section section : sections) {
            String sectionText = strategy.getResultantText(section);
            Files.write(Paths.get(String.format(format, page, i)), sectionText.getBytes("UTF8"));

            builder.append("--\n")
                    .append(sectionText)
                    .append('\n');
            i++;
        }
        builder.append("\n\n");
    }

    return builder.toString();
}
 
Example #22
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static BaseColor pickColor()
{
    colorIndex++;
    if (colorIndex >= colors.length)
        colorIndex = 0;
    return colors[colorIndex];
}
 
Example #23
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35374912/itext-cleaning-up-text-in-rectangle-without-cleaning-full-row">
 * iText - Cleaning Up Text in Rectangle without cleaning full row
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/zeljo2k8tly7yqi/Test1.pdf?dl=0">
 * Test1.pdf
 * </a>
 * <p>
 * With this new file the issue could be reproduced, indeed an iText issue.
 * </p>
 */
@Test
public void testRedactJavishsTest1() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Test1.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Test1-redactedJavish.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        List<Float> linkBounds = new ArrayList<Float>();
        linkBounds.add(0, (float) 202.3);
        linkBounds.add(1, (float) 588.6);
        linkBounds.add(2, (float) 265.8);
        linkBounds.add(3, (float) 599.7);

        Rectangle linkLocation1 = new Rectangle(linkBounds.get(0), linkBounds.get(1), linkBounds.get(2), linkBounds.get(3));
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        cleanUpLocations.add(new PdfCleanUpLocation(1, linkLocation1, BaseColor.GRAY));

        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();

        stamper.close();
        reader.close();
    }
}
 
Example #24
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35374912/itext-cleaning-up-text-in-rectangle-without-cleaning-full-row">
 * iText - Cleaning Up Text in Rectangle without cleaning full row
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/3i7g4w85dvul6db/input.pdf?dl=0">
 * input.pdf
 * </a>
 * <p>
 * Cannot reproduce the OP's issue.
 * </p>
 */
@Test
public void testRedactJavishsInput() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("input.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "input-redactedJavish.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        List<Float> linkBounds = new ArrayList<Float>();
        linkBounds.add(0, (float) 200.7);
        linkBounds.add(1, (float) 547.3);
        linkBounds.add(2, (float) 263.3);
        linkBounds.add(3, (float) 558.4);

        Rectangle linkLocation1 = new Rectangle(linkBounds.get(0), linkBounds.get(1), linkBounds.get(2), linkBounds.get(3));
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        cleanUpLocations.add(new PdfCleanUpLocation(1, linkLocation1, BaseColor.GRAY));

        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();

        stamper.close();
        reader.close();
    }
}
 
Example #25
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
protected Font createFont(TextChunk textChunk) {
	Font font = new Font(chineseFont);
	if (textChunk.getFontColor() != null) {
		int[] colors = textChunk.getFontColor();
		font.setColor(new BaseColor(colors[0], colors[1], colors[2]));
	}
	if (textChunk.getFontSize() > 0) {
		font.setSize(textChunk.getFontSize());
	}
	font.setStyle(textChunk.getFontStyle());
	return font;
}
 
Example #26
Source File: CellBorderEvent.java    From ureport with Apache License 2.0 5 votes vote down vote up
private PdfContentByte bulidCellBorder(PdfContentByte[] canvases,Border border){
	PdfContentByte cb=canvases[PdfPTable.LINECANVAS];
	cb.saveState();
	BigDecimal w=new BigDecimal(border.getWidth());
	cb.setLineWidth(w.divide(new BigDecimal(2),10,RoundingMode.HALF_UP).floatValue());
	if(border.getStyle().equals(BorderStyle.dashed)){
		cb.setLineDash(new float[]{2f,3f,1f},2);
	}
	String borderColor[]=border.getColor().split(",");
	cb.setColorStroke(new BaseColor(Integer.valueOf(borderColor[0]),Integer.valueOf(borderColor[1]),Integer.valueOf(borderColor[2])));
	return cb;
}
 
Example #27
Source File: PDFSampleMain.java    From tutorials with MIT License 5 votes vote down vote up
private static void addTableHeader(PdfPTable table) {
    Stream.of("column header 1", "column header 2", "column header 3")
    .forEach(columnTitle -> {
        PdfPCell header = new PdfPCell();
        header.setBackgroundColor(BaseColor.LIGHT_GRAY);
        header.setBorderWidth(2);
        header.setPhrase(new Phrase(columnTitle));
        table.addCell(header);
    });
}
 
Example #28
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testMultiUseRedactionImage() throws DocumentException, IOException
{
    byte[] simple = createMultiUseImagePdf();
    Files.write(new File(OUTPUTDIR, "multiUseImage.pdf").toPath(), simple);

    byte[] redacted = cleanUp(simple, Collections.singletonList(new PdfCleanUpLocation(1, new Rectangle(97f, 405f, 480f, 445f), BaseColor.GRAY)));
    Files.write(new File(OUTPUTDIR, "multiUseImageRedacted.pdf").toPath(), redacted);
}
 
Example #29
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSMaskRedactionImage() throws DocumentException, IOException
{
    byte[] simple = createSmaskImagePdf();
    Files.write(new File(OUTPUTDIR, "smaskImage.pdf").toPath(), simple);

    byte[] redacted = cleanUp(simple, Collections.singletonList(new PdfCleanUpLocation(1, new Rectangle(97f, 405f, 480f, 445f), BaseColor.GRAY)));
    Files.write(new File(OUTPUTDIR, "smaskImageRedacted.pdf").toPath(), redacted);
}
 
Example #30
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSimpleRedactionImage() throws DocumentException, IOException
{
    byte[] simple = createSimpleImagePdf();
    Files.write(new File(OUTPUTDIR, "simpleImage.pdf").toPath(), simple);

    byte[] redacted = cleanUp(simple, Collections.singletonList(new PdfCleanUpLocation(1, new Rectangle(97f, 405f, 480f, 445f), BaseColor.GRAY)));
    Files.write(new File(OUTPUTDIR, "simpleImageRedacted.pdf").toPath(), redacted);
}