org.apache.pdfbox.util.Matrix Java Examples

The following examples show how to use org.apache.pdfbox.util.Matrix. 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: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private AffineTransform calculateMatrix(PDRectangle bbox, int rotation)
{
    if (rotation == 0)
    {
        return new AffineTransform();
    }
    float tx = 0, ty = 0;
    switch (rotation)
    {
        case 90:
            tx = bbox.getUpperRightY();
            break;
        case 180:
            tx = bbox.getUpperRightY();
            ty = bbox.getUpperRightX();
            break;
        case 270:
            ty = bbox.getUpperRightX();
            break;
        default:
            break;
    }
    Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), tx, ty);
    return matrix.createAffineTransform();

}
 
Example #2
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then set the crop
 * box and media box to the bounding rectangle of the rotated page area.
 * </p>
 */
@Test
public void testRotateExpandBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
        page.setCropBox(newBox);
        page.setMediaBox(newBox);

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf"));
    }
}
 
Example #3
Source File: Concatenate.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void process(Operator operator, List<COSBase> arguments) throws IOException
{
    if (arguments.size() < 6)
    {
        throw new MissingOperandException(operator, arguments);
    }
    if (!checkArrayTypesClass(arguments, COSNumber.class))
    {
        return;
    }
    
    // concatenate matrix to current transformation matrix
    COSNumber a = (COSNumber) arguments.get(0);
    COSNumber b = (COSNumber) arguments.get(1);
    COSNumber c = (COSNumber) arguments.get(2);
    COSNumber d = (COSNumber) arguments.get(3);
    COSNumber e = (COSNumber) arguments.get(4);
    COSNumber f = (COSNumber) arguments.get(5);

    Matrix matrix = new Matrix(a.floatValue(), b.floatValue(), c.floatValue(),
                               d.floatValue(), e.floatValue(), f.floatValue());

    context.getGraphicsState().getCurrentTransformationMatrix().concatenate(matrix);
}
 
Example #4
Source File: ShadingContext.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param shading the shading type to be used
 * @param cm the color model to be used
 * @param xform transformation for user to device space
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @throws java.io.IOException if there is an error getting the color space
 * or doing background color conversion.
 */
public ShadingContext(PDShading shading, ColorModel cm, AffineTransform xform,
                      Matrix matrix) throws IOException
{
    this.shading = shading;
    shadingColorSpace = shading.getColorSpace();

    // create the output color model using RGB+alpha as color space
    ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT,
            DataBuffer.TYPE_BYTE);

    // get background values if available
    COSArray bg = shading.getBackground();
    if (bg != null)
    {
        background = bg.toFloatArray();
        rgbBackground = convertToRGB(background);
    }
}
 
Example #5
Source File: PDPageContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the x,y coordinates, with the given size.
 *
 * @param image The image to draw.
 * @param x The x-coordinate to draw the image.
 * @param y The y-coordinate to draw the image.
 * @param width The width to draw the image.
 * @param height The height to draw the image.
 *
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was called within a text block.
 */
public void drawImage(PDImageXObject image, float x, float y, float width, float height) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = new AffineTransform(width, 0, 0, height, x, y);
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #6
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box
 * and then crop it to make all previously visible content fit.
 * </p>
 */
@Test
public void testRotateCenterScale() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);

        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        float scale = Math.min(cropBox.getWidth() / (float)rectangle.getWidth(), cropBox.getHeight() / (float)rectangle.getHeight());

        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(matrix);
        cs.transform(Matrix.getScaleInstance(scale, scale));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center-scale.pdf"));
    }
}
 
Example #7
Source File: GraphicsParser.java    From tephra with MIT License 6 votes vote down vote up
private boolean clip(Matrix matrix, PDImageXObject pdImageXObject) throws IOException {
    if (clipTypes.isEmpty() || (clipTypes.size() == 1 && clipTypes.get(0).equals("rect")
            && Math.abs(matrix.getScaleX() / matrix.getScalingFactorY()
            - (clipArea[2] - clipArea[0]) / (clipArea[3] - clipArea[1])) <= 0.01D))
        return false;

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(GenericDOMImplementation.getDOMImplementation()
            .createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null));
    if (pdImageXObject != null) {
        int w = (int) matrix.getScalingFactorX();
        int h = (int) matrix.getScalingFactorY();
        svgGraphics2D.clip(getPath(clipTypes, clipPoints, clipArea));
        svgGraphics2D.drawImage(pdImageXObject.getImage().getScaledInstance(w, h, Image.SCALE_SMOOTH),
                (int) (matrix.getTranslateX() - clipArea[0]), (int) (matrix.getTranslateY() - clipArea[1]), w, h, null);
    }
    save(svgGraphics2D, clipArea[0], clipArea[1], (clipArea[2] - clipArea[0]), (clipArea[3] - clipArea[1]));

    return true;
}
 
Example #8
Source File: LegacyPDFStreamEngine.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will initialize and process the contents of the stream.
 *
 * @param page the page to process
 * @throws java.io.IOException if there is an error accessing the stream.
 */
@Override
public void processPage(PDPage page) throws IOException
{
    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();

    if (pageSize.getLowerLeftX() == 0 && pageSize.getLowerLeftY() == 0)
    {
        translateMatrix = null;
    }
    else
    {
        // translation matrix for cropbox
        translateMatrix = Matrix.getTranslateInstance(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
    }
    super.processPage(page);
}
 
Example #9
Source File: PDPageContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the origin with the given transformation matrix.
 *
 * @param image The image to draw.
 * @param matrix The transformation matrix to apply to the image.
 *
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was called within a text block.
 */
public void drawImage(PDImageXObject image, Matrix matrix) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = matrix.createAffineTransform();
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #10
Source File: PDTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void drawStar(PDAnnotationText annotation, final PDAppearanceContentStream contentStream)
        throws IOException
{
    PDRectangle bbox = adjustRectAndBBox(annotation, 20, 19);

    float min = Math.min(bbox.getWidth(), bbox.getHeight());

    contentStream.setMiterLimit(4);
    contentStream.setLineJoinStyle(1);
    contentStream.setLineCapStyle(0);
    contentStream.setLineWidth(0.59f); // value from Adobe

    contentStream.transform(Matrix.getScaleInstance(0.001f * min / 0.8f, 0.001f * min / 0.8f));

    // we get the shape of a Zapf Dingbats star (0x2605) and use that one.
    // Adobe uses a different font (which one?), or created the shape from scratch.
    GeneralPath path = PDType1Font.ZAPF_DINGBATS.getPath("a35");
    addPath(contentStream, path);
    contentStream.fillAndStroke();
}
 
Example #11
Source File: PDFBoxTree.java    From Pdf2Dom with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Rectangle2D calculateImagePosition(PDImageXObject pdfImage) throws IOException
{
    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
    Rectangle2D imageBounds = pdfImage.getImage().getRaster().getBounds();

    AffineTransform imageTransform = new AffineTransform(ctm.createAffineTransform());
    imageTransform.scale(1.0 / pdfImage.getWidth(), -1.0 / pdfImage.getHeight());
    imageTransform.translate(0, -pdfImage.getHeight());

    AffineTransform pageTransform = createCurrentPageTransformation();
    pageTransform.concatenate(imageTransform);

    return pageTransform.createTransformedShape(imageBounds).getBounds2D();
}
 
Example #12
Source File: PDTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void drawUpLeftArrow(PDAnnotationText annotation, final PDAppearanceContentStream contentStream)
             throws IOException
{
    adjustRectAndBBox(annotation, 17, 17);

    contentStream.setMiterLimit(4);
    contentStream.setLineJoinStyle(1);
    contentStream.setLineCapStyle(0);
    contentStream.setLineWidth(0.59f); // value from Adobe
    
    contentStream.transform(Matrix.getRotateInstance(Math.toRadians(45), 8, -4));

    contentStream.moveTo(1, 7);
    contentStream.lineTo(5, 7);
    contentStream.lineTo(5, 1);
    contentStream.lineTo(12, 1);
    contentStream.lineTo(12, 7);
    contentStream.lineTo(16, 7);
    contentStream.lineTo(8.5f, 19);
    contentStream.closeAndFillAndStroke();
}
 
Example #13
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void rotateSignature(PDPageContentStream cs, PDRectangle rectangle, SignatureFieldDimensionAndPosition dimensionAndPosition) throws IOException {
   	switch (dimensionAndPosition.getGlobalRotation()) {
		case ImageRotationUtils.ANGLE_90:
			// pdfbox rotates in the opposite way
	    	cs.transform(Matrix.getRotateInstance(Math.toRadians(ImageRotationUtils.ANGLE_270), 0, 0));
	    	cs.transform(Matrix.getTranslateInstance(-rectangle.getHeight(), 0));
			break;
		case ImageRotationUtils.ANGLE_180:
	    	cs.transform(Matrix.getRotateInstance(Math.toRadians(ImageRotationUtils.ANGLE_180), 0, 0));
	    	cs.transform(Matrix.getTranslateInstance(-rectangle.getWidth(), -rectangle.getHeight()));
			break;
		case ImageRotationUtils.ANGLE_270:
	    	cs.transform(Matrix.getRotateInstance(Math.toRadians(ImageRotationUtils.ANGLE_90), 0, 0));
	    	cs.transform(Matrix.getTranslateInstance(0, -rectangle.getWidth()));
			break;
		case ImageRotationUtils.ANGLE_360:
			// do nothing
			break;
		default:
               throw new IllegalStateException(ImageRotationUtils.SUPPORTED_ANGLES_ERROR_MESSAGE);
	}
}
 
Example #14
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the origin with the given transformation matrix.
 *
 * @param image The image to draw.
 * @param matrix The transformation matrix to apply to the image.
 *
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was called within a text block.
 */
public void drawImage(PDImageXObject image, Matrix matrix) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = matrix.createAffineTransform();
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #15
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the x,y coordinates, with the given size.
 *
 * @param image The image to draw.
 * @param x The x-coordinate to draw the image.
 * @param y The y-coordinate to draw the image.
 * @param width The width to draw the image.
 * @param height The height to draw the image.
 *
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was called within a text block.
 */
public void drawImage(PDImageXObject image, float x, float y, float width, float height) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = new AffineTransform(width, 0, 0, height, x, y);
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #16
Source File: PDTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void drawRightPointer(PDAnnotationText annotation, final PDAppearanceContentStream contentStream)
        throws IOException
{
    PDRectangle bbox = adjustRectAndBBox(annotation, 20, 17);

    float min = Math.min(bbox.getWidth(), bbox.getHeight());

    contentStream.setMiterLimit(4);
    contentStream.setLineJoinStyle(1);
    contentStream.setLineCapStyle(0);
    contentStream.setLineWidth(0.59f); // value from Adobe

    contentStream.transform(Matrix.getScaleInstance(0.001f * min / 0.8f, 0.001f * min / 0.8f));
    contentStream.transform(Matrix.getTranslateInstance(0, 50));

    // we get the shape of a Zapf Dingbats right pointer (0x27A4) and use that one.
    // Adobe uses a different font (which one?), or created the shape from scratch.
    GeneralPath path = PDType1Font.ZAPF_DINGBATS.getPath("a174");
    addPath(contentStream, path);
    contentStream.fillAndStroke();
}
 
Example #17
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private PDAppearanceStream prepareNormalAppearanceStream(PDAnnotationWidget widget)
{
    PDAppearanceStream appearanceStream = new PDAppearanceStream(field.getAcroForm().getDocument());

    // Calculate the entries for the bounding box and the transformation matrix
    // settings for the appearance stream
    int rotation = resolveRotation(widget);
    PDRectangle rect = widget.getRectangle();
    Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0);
    Point2D.Float point2D = matrix.transformPoint(rect.getWidth(), rect.getHeight());

    PDRectangle bbox = new PDRectangle(Math.abs((float) point2D.getX()), Math.abs((float) point2D.getY()));
    appearanceStream.setBBox(bbox);

    AffineTransform at = calculateMatrix(bbox, rotation);
    if (!at.isIdentity())
    {
        appearanceStream.setMatrix(at);
    }
    appearanceStream.setFormType(1);
    appearanceStream.setResources(new PDResources());
    return appearanceStream;
}
 
Example #18
Source File: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
PDDocument createTextDocument(PDRectangle size, Matrix textMatrix, String... lines) throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(size);
    document.addPage(page);

    try (PDPageContentStream canvas = new PDPageContentStream(document, page)) {
        canvas.beginText();
        canvas.setTextMatrix(textMatrix);
        canvas.setFont(PDType1Font.HELVETICA_BOLD, 12);
        canvas.setLeading(14);
        for (String line : lines) {
            canvas.showText(line);
            canvas.newLine();
        }
        canvas.endText();
    }

    return document;
}
 
Example #19
Source File: PdfGenerator.java    From blog-tutorials with MIT License 6 votes vote down vote up
public byte[] createPdf() throws IOException {
  try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    PDImageXObject chartImage = JPEGFactory.createFromImage(document,
      createChart((int) pageHeight, (int) pageWidth));

    contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
    contentStream.drawImage(chartImage, 0, 0);
    contentStream.close();

    document.addPage(page);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
  }

}
 
Example #20
Source File: TriangleBasedShadingContext.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param shading the shading type to be used
 * @param cm the color model to be used
 * @param xform transformation for user to device space
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @throws IOException if there is an error getting the color space or doing background color conversion.
 */
TriangleBasedShadingContext(PDShading shading, ColorModel cm, AffineTransform xform,
                                   Matrix matrix) throws IOException
{
    super(shading, cm, xform, matrix);
    PDTriangleBasedShadingType triangleBasedShadingType = (PDTriangleBasedShadingType) shading;
    hasFunction = shading.getFunction() != null;
    bitsPerCoordinate = triangleBasedShadingType.getBitsPerCoordinate();
    LOG.debug("bitsPerCoordinate: " + (Math.pow(2, bitsPerCoordinate) - 1));
    bitsPerColorComponent = triangleBasedShadingType.getBitsPerComponent();
    LOG.debug("bitsPerColorComponent: " + bitsPerColorComponent);
    numberOfColorComponents = hasFunction ? 1 : getShadingColorSpace().getNumberOfComponents();
    LOG.debug("numberOfColorComponents: " + numberOfColorComponents);
}
 
Example #21
Source File: EditPageContent.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38498431/how-to-remove-filtered-content-from-a-pdf-with-itext">
 * How to remove filtered content from a PDF with iText
 * </a>
 * <br/>
 * <a href="https://1drv.ms/b/s!AmNST-TRoPSemi2k0UnGFsjQM1Yt">
 * document.pdf
 * </a>
 * <p>
 * This test shows how to remove text filtered by actual font size.
 * </p>
 */
@Test
public void testRemoveBigTextDocument() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            PDDocument document = Loader.loadPDF(resource)) {
        for (PDPage page : document.getDocumentCatalog().getPages()) {
            PdfContentStreamEditor identity = new PdfContentStreamEditor(document, page) {
                @Override
                protected void write(ContentStreamWriter contentStreamWriter, Operator operator, List<COSBase> operands) throws IOException {
                    String operatorString = operator.getName();

                    if (TEXT_SHOWING_OPERATORS.contains(operatorString))
                    {
                        float fs = getGraphicsState().getTextState().getFontSize();
                        Matrix matrix = getTextMatrix().multiply(getGraphicsState().getCurrentTransformationMatrix());
                        Point2D.Float transformedFsVector = matrix.transformPoint(0, fs);
                        Point2D.Float transformedOrigin = matrix.transformPoint(0, 0);
                        double transformedFs = transformedFsVector.distance(transformedOrigin);
                        if (transformedFs > 100)
                            return;
                    }

                    super.write(contentStreamWriter, operator, operands);
                }

                final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj", "'", "\"", "TJ");
            };
            identity.processPage(page);
        }
        document.save(new File(RESULT_FOLDER, "document-noBigText.pdf"));
    }
}
 
Example #22
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void showType3Glyph(Matrix textRenderingMatrix, PDType3Font font, int code,
        String unicode, Vector displacement) throws IOException
{
    PDGraphicsState state = getGraphicsState();
    RenderingMode renderingMode = state.getTextState().getRenderingMode();
    if (!RenderingMode.NEITHER.equals(renderingMode))
    {
        super.showType3Glyph(textRenderingMatrix, font, code, unicode, displacement);
    }
}
 
Example #23
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void adjustRectangle(Rectangle2D r)
{
    Matrix m = new Matrix(xform);
    float scaleX = Math.abs(m.getScalingFactorX());
    float scaleY = Math.abs(m.getScalingFactorY());

    AffineTransform adjustedTransform = new AffineTransform(xform);
    adjustedTransform.scale(1.0 / scaleX, 1.0 / scaleY);
    r.setRect(adjustedTransform.createTransformedShape(r).getBounds2D());
}
 
Example #24
Source File: PDFStreamEngine.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Processes a transparency group stream.
 * 
 * @param group the transparency group.
 * 
 * @throws IOException
 */
protected void processTransparencyGroup(PDTransparencyGroup group) throws IOException
{
    if (currentPage == null)
    {
        throw new IllegalStateException("No current page, call " +
                "#processChildStream(PDContentStream, PDPage) instead");
    }

    PDResources parent = pushResources(group);
    Deque<PDGraphicsState> savedStack = saveGraphicsStack();
    
    Matrix parentMatrix = initialMatrix;

    // the stream's initial matrix includes the parent CTM, e.g. this allows a scaled form
    initialMatrix = getGraphicsState().getCurrentTransformationMatrix().clone();

    // transform the CTM using the stream's matrix
    getGraphicsState().getCurrentTransformationMatrix().concatenate(group.getMatrix());

    // Before execution of the transparency group XObject’s content stream, 
    // the current blend mode in the graphics state shall be initialized to Normal, 
    // the current stroking and nonstroking alpha constants to 1.0, and the current soft mask to None.
    getGraphicsState().setBlendMode(BlendMode.NORMAL);
    getGraphicsState().setAlphaConstant(1);
    getGraphicsState().setNonStrokeAlphaConstant(1);
    getGraphicsState().setSoftMask(null);

    // clip to bounding box
    clipToRect(group.getBBox());

    processStreamOperators(group);
    
    initialMatrix = parentMatrix;

    restoreGraphicsStack(savedStack);
    popResources(parent);
}
 
Example #25
Source File: PDCalRGB.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets the linear interpretation matrix.
 * Passing in null will clear the matrix.
 * @param matrix the new linear interpretation matrix, or null
 */
public final void setMatrix(Matrix matrix)
{
    COSArray matrixArray = null;
    if(matrix != null)
    {
        matrixArray = matrix.toCOSArray();
    }
    dictionary.setItem(COSName.MATRIX, matrixArray);
}
 
Example #26
Source File: BoundingBoxFinder.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)
        throws IOException {
    super.showGlyph(textRenderingMatrix, font, code, displacement);
    Shape shape = calculateGlyphBounds(textRenderingMatrix, font, code);
    if (shape != null) {
        Rectangle2D rect = shape.getBounds2D();
        add(rect);
    }
}
 
Example #27
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is the OP's original code. It mirrors the image.
 * This can be fixed as shown in {@link #testImageAppendNoMirror()}.
 * </p>
 */
@Test
public void testImageAppendLikeShanky() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

        PDPage page = doc.getPage(0);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2;
        float y_adjusted = ( y_pos - h ) / 2;

        Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
        contentStream.transform(mt);
        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-shanky.pdf"));
        doc.close();

    }
}
 
Example #28
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * The Tm operator. Sets the text matrix to the given values.
 * A current text matrix will be replaced with the new one.
 *
 * @param matrix the transformation matrix
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was not allowed to be called at this time.
 */
public void setTextMatrix(Matrix matrix) throws IOException
{
    if (!inTextMode)
    {
        throw new IllegalStateException("Error: must call beginText() before setTextMatrix");
    }
    writeAffineTransform(matrix.createAffineTransform());
    writeOperator(OperatorName.SET_MATRIX);
}
 
Example #29
Source File: GouraudShadingContext.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Read a vertex from the bit input stream performs interpolations.
 *
 * @param input bit input stream
 * @param maxSrcCoord max value for source coordinate (2^bits-1)
 * @param maxSrcColor max value for source color (2^bits-1)
 * @param rangeX dest range for X
 * @param rangeY dest range for Y
 * @param colRangeTab dest range array for colors
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @return a new vertex with the flag and the interpolated values
 * @throws IOException if something went wrong
 */
protected Vertex readVertex(ImageInputStream input, long maxSrcCoord, long maxSrcColor,
                            PDRange rangeX, PDRange rangeY, PDRange[] colRangeTab,
                            Matrix matrix, AffineTransform xform) throws IOException
{
    float[] colorComponentTab = new float[numberOfColorComponents];
    long x = input.readBits(bitsPerCoordinate);
    long y = input.readBits(bitsPerCoordinate);
    float dstX = interpolate(x, maxSrcCoord, rangeX.getMin(), rangeX.getMax());
    float dstY = interpolate(y, maxSrcCoord, rangeY.getMin(), rangeY.getMax());
    LOG.debug("coord: " + String.format("[%06X,%06X] -> [%f,%f]", x, y, dstX, dstY));
    Point2D p = matrix.transformPoint(dstX, dstY);
    xform.transform(p, p);

    for (int n = 0; n < numberOfColorComponents; ++n)
    {
        int color = (int) input.readBits(bitsPerColorComponent);
        colorComponentTab[n] = interpolate(color, maxSrcColor, colRangeTab[n].getMin(),
                colRangeTab[n].getMax());
        LOG.debug("color[" + n + "]: " + color + "/" + String.format("%02x", color)
                + "-> color[" + n + "]: " + colorComponentTab[n]);
    }

    // "Each set of vertex data shall occupy a whole number of bytes.
    // If the total number of bits required is not divisible by 8, the last data byte
    // for each vertex is padded at the end with extra bits, which shall be ignored."
    int bitOffset = input.getBitOffset();
    if (bitOffset != 0)
    {
        input.readBits(8 - bitOffset);
    }

    return new Vertex(p, colorComponentTab);
}
 
Example #30
Source File: HelloSignManipulator.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException
{
    if (replacement != null)
    {
        boolean copy = true;
        if (TjTJ.contains(operator.getName()))
        {
            Matrix transformation = getTextMatrix().multiply(getGraphicsState().getCurrentTransformationMatrix());
            float xPos = transformation.getTranslateX();
            float yPos = transformation.getTranslateY();
            for (HelloSignField field : fields)
            {
                if (field.inField(xPos, yPos))
                {
                    copy = false;
                }
            }
        }

        if (copy)
        {
            replacement.writeTokens(operands);
            replacement.writeToken(operator);
        }
    }
    super.processOperator(operator, operands);
}