com.itextpdf.text.pdf.PdfContentByte Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfContentByte. 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: 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 #4
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 #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: 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 #7
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 #8
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 #9
Source File: PlotUtils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports the specified JFreeChart to a PDF file using
 * <a href="http://itextpdf.com" target="_blank">iText</a>, bundled with
 * Fiji. The destination file is specified by the user in a save dialog
 * prompt. An error message is displayed if the file could not be saved.
 * Does nothing if {@code chart} is {@code null}.
 *
 * @param chart
 *            the <a href="http://javadoc.imagej.net/JFreeChart/" target=
 *            "_blank">JFreeChart </a> to export.
 * @param bounds
 *            the Rectangle delimiting the boundaries within which the chart
 *            should be drawn.
 * @see #exportChartAsPDF(JFreeChart, Rectangle)
 * @see #exportChartAsSVG(JFreeChart, Rectangle)
 * @see #exportChartAsSVG(JFreeChart, Rectangle, File)
 */
public static void exportChartAsPDF(final JFreeChart chart, final Rectangle bounds, final File f)
		throws FileNotFoundException, DocumentException {

	final int margin = 0; // page margins

	// Initialize writer
	final Document document = new Document(new com.itextpdf.text.Rectangle(bounds.width, bounds.height), margin,
			margin, margin, margin);
	final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));

	document.open();
	final PdfContentByte cb = writer.getDirectContent();
	final PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

	// Draw the chart. Release resources upon completion
	final Graphics2D g2 = tp.createGraphics(bounds.width, bounds.height, new DefaultFontMapper());
	chart.draw(g2, bounds);
	g2.dispose();

	// Write to file
	cb.addTemplate(tp, 0, 0);

	document.close();
}
 
Example #10
Source File: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example #11
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 #12
Source File: StampInLayer.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException
{
    PdfReader reader = new PdfReader(_pdfFile);

    try (   ByteArrayOutputStream ms = new ByteArrayOutputStream()  )
    {
        PdfStamper stamper = new PdfStamper(reader, ms);
        //Don't delete otherwise the stamper flattens the layers
        if (readLayers)
            stamper.getPdfLayers();

        PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter());
        PdfContentByte cb = stamper.getUnderContent(1);
        cb.beginLayer(logoLayer);

        //300dpi
        iImage.scalePercent(24f);
        iImage.setAbsolutePosition(x, y);
        cb.addImage(iImage);

        cb.endLayer();
        stamper.close();

        return (ms.toByteArray());
    }
}
 
Example #13
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 #14
Source File: UseColumnText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
 * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
 * </a>
 * <p>
 * Indeed, the coordinates do not line up. The y coordinate of 
 * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
 * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
 * the text to come.
 * </p>
 */
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
    document.open();

    Font fontQouteItems = new Font(BaseFont.createFont(), 12);
    PdfContentByte canvas = writer.getDirectContent();

    // Item Number
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);

    // Estimated Qty
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);

    // Item Description
    ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
    ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
    ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
    ct.go();

    document.close();
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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,
 * cf. {@link #testLikeUser3208131()}. The reason is that the op is working in
 * text mode. Thus, he has to use {@link ColumnText#setLeading(float, float)}
 * instead.
 * </p>
 */
@Test
public void testLikeUser3208131Fixed() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131-fixed.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() };

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

    document.close();
}
 
Example #20
Source File: AddRotatedImage.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
void addRotatedImage(PdfContentByte contentByte, Image image, float x, float y, float width, float height, float rotation) throws DocumentException
{
    // Draw image at x,y without rotation
    contentByte.addImage(image, width, 0, 0, height, x, y);

    // Draw image as if the previous image was 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);
    // Stretch it to its dimensions
    AffineTransform B = AffineTransform.getScaleInstance(width, height);
    // Rotate it
    AffineTransform C = AffineTransform.getRotateInstance(rotation);
    // Move it to have the same center as above
    AffineTransform D = AffineTransform.getTranslateInstance(x + width/2, y + height/2);
    // Concatenate
    AffineTransform M = (AffineTransform) A.clone();
    M.preConcatenate(B);
    M.preConcatenate(C);
    M.preConcatenate(D);
    //Draw
    contentByte.addImage(image, M);
}
 
Example #21
Source File: AppearanceAndRotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example #22
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 #23
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 #24
Source File: TextLocationExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void mark(InputStream input, OutputStream output, Pattern pattern) throws DocumentException, IOException
{
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    try {
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        for (int pageNr = 1; pageNr <= reader.getNumberOfPages(); pageNr++)
        {
            SearchTextLocationExtractionStrategy strategy = new SearchTextLocationExtractionStrategy(pattern);
            parser.processContent(pageNr, strategy, Collections.emptyMap()).getResultantText();
            Collection<TextRectangle> locations = strategy.getLocations(null);
            if (locations.isEmpty())
                continue;

            PdfContentByte canvas = stamper.getOverContent(pageNr);
            canvas.setRGBColorStroke(255, 255, 0);
            for (TextRectangle location : locations)
            {
                canvas.rectangle(location.getMinX(), location.getMinY(), location.getWidth(), location.getHeight());
            }
            canvas.stroke();
        }
        stamper.close();
    } finally {
        reader.close();
    }
}
 
Example #25
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 #26
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 #27
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void test(String resource, float minWidth, float minHeight) throws IOException, DocumentException
{
    String name = new File(resource).getName();
    String target = String.format("%s-freeSpace%.0fx%.0f.pdf", name, minWidth, minHeight);
    InputStream resourceStream = getClass().getResourceAsStream(resource);
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        System.out.printf("\nFree %.0fx%.0f regions in %s\n", minWidth, minHeight, name);

        Collection<Rectangle2D> rectangles = find(reader, minWidth, minHeight, 1);
        print(rectangles);

        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, target)));
        PdfContentByte over = stamper.getOverContent(1);

        enhance(over, rectangles);
        Point2D[] points = getPointsOfInterest(reader.getCropBox(1));
        for (int i = 0; i < points.length; i++)
            enhance(over, rectangles, points[i], colors[i]);

        stamper.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #28
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 #29
Source File: ChartExportUtil.java    From mzmine2 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 #30
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();
}