List of usage examples for org.apache.pdfbox.util Matrix Matrix
public Matrix()
From source file:airviewer.AnnotationGenerator.java
/** * * @param a// w w w .j av a 2 s . co m * @param d * @param p * @param shouldResize * @return */ public static PDAppearanceStream generateSquareAppearance(PDAnnotation a, PDDocument d, PDPage p, boolean shouldResize) { assert null != a; assert null != d; assert null != p; PDAppearanceStream annotationAppearanceStream = null; try { if (shouldResize) { resizeAnnotationToContent(a); } final String contents = a.getContents(); final boolean hasContents = null != contents && 0 < contents.length(); float borderWidth = 0; if (a instanceof PDAnnotationMarkup) { final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle(); if (null != a.getColor() && null != borderStyle) { borderWidth = Math.abs(borderStyle.getWidth()); } } final float fontSize = FONT_SIZE_PDF_POINTS; final float textHeight = fontSize; final float margin = MARGIN_SIZE_PDF_POINTS; PDRectangle position = a.getRectangle(); final float lowerLeftX = position.getLowerLeftX(); final float lowerLeftY = position.getLowerLeftY(); float width = position.getWidth(); float height = position.getHeight(); annotationAppearanceStream = new PDAppearanceStream(d); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(p.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) { appearanceContent.transform(new Matrix()); // Identity transform // Rect is inset by half border width to prevent border leaking // outside bounding box final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f; final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f; final float insetWidth = width - borderWidth; final float insetheight = height - borderWidth; appearanceContent.addRect(insetLowerLeftX, insetLowerLeftY, insetWidth, insetheight); appearanceContent.setLineWidth(borderWidth); appearanceContent.setNonStrokingColor(GRAY); if (null != a.getColor() && 0 < borderWidth) { appearanceContent.setStrokingColor(a.getColor()); appearanceContent.fillAndStroke(); } else { appearanceContent.fill(); } if (hasContents) { appearanceContent.moveTo(0, 0); appearanceContent.beginText(); // Center vertically, left justified inside border with margin appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin, lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f); appearanceContent.setFont(FONT, fontSize); if (null != a.getColor()) { appearanceContent.setNonStrokingColor(a.getColor()); // Sets color of text } else { appearanceContent.setNonStrokingColor(BLACK); // Sets color of text } appearanceContent.showText(a.getContents()); appearanceContent.endText(); } } } catch (IOException ex) { Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex); } return annotationAppearanceStream; }
From source file:airviewer.AnnotationGenerator.java
/** * * @param a//ww w. j a va2s .c om * @param d * @param p * @param shouldResize * @return */ public static PDAppearanceStream generateCircleAppearance(PDAnnotation a, PDDocument d, PDPage p, boolean shouldResize) { assert null != a; assert null != d; assert null != p; PDAppearanceStream annotationAppearanceStream = null; try { if (shouldResize) { resizeAnnotationToContent(a); } final String contents = a.getContents(); final boolean hasContents = null != contents && 0 < contents.length(); float borderWidth = 0; if (a instanceof PDAnnotationMarkup) { final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle(); if (null != a.getColor() && null != borderStyle) { borderWidth = Math.abs(borderStyle.getWidth()); } } final float fontSize = FONT_SIZE_PDF_POINTS; final float textHeight = fontSize; final float margin = MARGIN_SIZE_PDF_POINTS; PDRectangle position = a.getRectangle(); final float lowerLeftX = position.getLowerLeftX(); final float lowerLeftY = position.getLowerLeftY(); float width = position.getWidth(); float height = position.getHeight(); annotationAppearanceStream = new PDAppearanceStream(d); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(p.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) { appearanceContent.transform(new Matrix()); // Identity transform // Rect is inset by half border width to prevent border leaking // outside bounding box final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f; final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f; final float insetWidth = width - borderWidth; final float insetheight = height - borderWidth; if (null != a.getColor()) { appearanceContent.setLineWidth(borderWidth); appearanceContent.moveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.5f); appearanceContent.curveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.75f, insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY + insetheight, insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY + insetheight); appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY + insetheight, insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.75f, insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.5f); appearanceContent.curveTo(insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.25f, insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY, insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY); appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY, insetLowerLeftX, insetLowerLeftY + insetheight * 0.25f, insetLowerLeftX, insetLowerLeftY + insetheight * 0.5f); } appearanceContent.setNonStrokingColor(GRAY); if (null != a.getColor() && 0 < borderWidth) { appearanceContent.setStrokingColor(a.getColor()); appearanceContent.fillAndStroke(); } else { appearanceContent.fill(); } if (hasContents) { appearanceContent.moveTo(0, 0); appearanceContent.beginText(); // Center text vertically, left justified inside border with margin appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin, lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f); appearanceContent.setFont(FONT, fontSize); appearanceContent.setNonStrokingColor(BLACK); // Sets color of text appearanceContent.showText(a.getContents()); appearanceContent.endText(); } } } catch (IOException ex) { Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex); } return annotationAppearanceStream; }
From source file:airviewer.BoxAnnotationMaker.java
License:Apache License
/** * * @param document//from www. j a v a 2 s . c o m * @param arguments(lowerLeftX, lowerLeftY, width, height) * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 5; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); float width = parseFloat(arguments.get(3)); float height = parseFloat(arguments.get(4)); String contents = ""; PDFont font = PDType1Font.HELVETICA_OBLIQUE; float fontSize = 16; // Or whatever font size you want. //float textWidth = font.getStringWidth(contents) * fontSize / 1000.0f; //float textHeight = 32; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + height); PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE); aSquare.setAnnotationName(new UID().toString()); aSquare.setContents(contents); aSquare.setColor(red); // Outline in red, not setting a fill PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aSquare.setInteriorColor(fillColor); aSquare.setBorderStyle(borderThick); aSquare.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // copy page.getAnnotations().add(aSquare); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aSquare.getAppearance()) { aSquare.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.addRect(lowerLeftX, lowerLeftY, width, height); appearanceContent.setLineWidth(borderThick.getWidth()); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.setStrokingColor(red); appearanceContent.fillAndStroke(); appearanceContent.beginText(); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + height * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.setNonStrokingColor(red); appearanceContent.showText(contents); appearanceContent.endText(); } aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream); } //System.out.println(page.getAnnotations().toString()); } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("\tNon number encountered where floating point number expected."); result = null; } return result; }
From source file:airviewer.EllipseAnnotationMaker.java
License:Apache License
/** * // www .j av a2 s.co m * @param document * @param arguments(pageNumber, lowerLeftX, lowerLeftY, width, height, contents) * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 6; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); float width = parseFloat(arguments.get(3)); float height = parseFloat(arguments.get(4)); String contents = arguments.get(5); PDFont font = PDType1Font.HELVETICA_OBLIQUE; final float fontSize = 16.0f; // Or whatever font size you want. //final float lineSpacing = 4.0f; width = max(width, font.getStringWidth(contents) * fontSize / 1000.0f); //final float textHeight = fontSize + lineSpacing; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDColor black = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + height); PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_CIRCLE); aCircle.setAnnotationName(new UID().toString()); aCircle.setContents(contents); PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aCircle.setInteriorColor(fillColor); aCircle.setColor(red); aCircle.setBorderStyle(borderThick); aCircle.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // Copy page.getAnnotations().add(aCircle); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aCircle.getAppearance()) { aCircle.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.moveTo(lowerLeftX, lowerLeftY + height * 0.5f); appearanceContent.curveTo(lowerLeftX, lowerLeftY + height * 0.75f, lowerLeftX + width * 0.25f, lowerLeftY + height, lowerLeftX + width * 0.5f, lowerLeftY + height); appearanceContent.curveTo(lowerLeftX + width * 0.75f, lowerLeftY + height, lowerLeftX + width, lowerLeftY + height * 0.75f, lowerLeftX + width, lowerLeftY + height * 0.5f); appearanceContent.curveTo(lowerLeftX + width, lowerLeftY + height * 0.25f, lowerLeftX + width * 0.75f, lowerLeftY, lowerLeftX + width * 0.5f, lowerLeftY); appearanceContent.curveTo(lowerLeftX + width * 0.25f, lowerLeftY, lowerLeftX, lowerLeftY + height * 0.25f, lowerLeftX, lowerLeftY + height * 0.5f); appearanceContent.setLineWidth(borderThick.getWidth()); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.setStrokingColor(red); appearanceContent.fillAndStroke(); appearanceContent.moveTo(0, 0); appearanceContent.beginText(); appearanceContent.setNonStrokingColor(black); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX + borderThick.getWidth(), lowerLeftY + height * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.showText(contents); appearanceContent.endText(); } aCircle.getAppearance().setNormalAppearance(annotationAppearanceStream); } } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("Non number encountered where floating point number expected."); result = null; } catch (IOException ex) { Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex); result = null; } return result; }
From source file:airviewer.TextAnnotationMaker.java
License:Apache License
/** * /*from w ww . j a va 2 s.c om*/ * @param document * @param arguments(pageNumber, lowerLeftX, lowerLeftY); String contents * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 4; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); String contents = arguments.get(3); PDFont font = PDType1Font.HELVETICA_OBLIQUE; final float fontSize = 16.0f; // Or whatever font size you want. final float lineSpacing = 4.0f; float width = font.getStringWidth(contents) * fontSize / 1000.0f; // font.getStringWidth(contents) returns thousanths of PS point final float textHeight = fontSize + lineSpacing; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + textHeight); PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE); aSquare.setAnnotationName(new UID().toString()); aSquare.setContents(contents); PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aSquare.setInteriorColor(fillColor); aSquare.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // copy page.getAnnotations().add(aSquare); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aSquare.getAppearance()) { aSquare.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + textHeight + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.addRect(lowerLeftX, lowerLeftY, width, textHeight); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.fill(); appearanceContent.beginText(); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + textHeight * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.setNonStrokingColor(red); appearanceContent.showText(contents); appearanceContent.endText(); } aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream); } //System.out.println(page.getAnnotations().toString()); } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("Non number encountered where floating point number expected."); result = null; } catch (IOException ex) { Logger.getLogger(TextAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex); result = null; } return result; }
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox.placeholder.SignaturePlaceholderExtractor.java
License:EUPL
@Override protected void processOperator(PDFOperator operator, List<COSBase> arguments) throws IOException { String operation = operator.getOperation(); if (operation.equals("Do")) { COSName objectName = (COSName) arguments.get(0); Map<?, ?> xobjects = getResources().getXObjects(); PDXObject xobject = (PDXObject) xobjects.get(objectName.getName()); if (xobject instanceof PDXObjectImage) { try { PDXObjectImage image = (PDXObjectImage) xobject; SignaturePlaceholderData data = checkImage(image); if (data != null) { PDPage page = getCurrentPage(); Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); int pageRotation = page.findRotation(); pageRotation = pageRotation % 360; double rotationInRadians = Math.toRadians(pageRotation);//(page.findRotation() * Math.PI) / 180; AffineTransform rotation = new AffineTransform(); rotation.setToRotation(rotationInRadians); AffineTransform rotationInverse = rotation.createInverse(); Matrix rotationInverseMatrix = new Matrix(); rotationInverseMatrix.setFromAffineTransform(rotationInverse); Matrix rotationMatrix = new Matrix(); rotationMatrix.setFromAffineTransform(rotation); Matrix unrotatedCTM = ctm.multiply(rotationInverseMatrix); float x = unrotatedCTM.getXPosition(); float yPos = unrotatedCTM.getYPosition(); float yScale = unrotatedCTM.getYScale(); float y = yPos + yScale; float w = unrotatedCTM.getXScale(); logger.debug("Page height: {}", page.findCropBox().getHeight()); logger.debug("Page width: {}", page.findCropBox().getWidth()); if (pageRotation == 90) { y = page.findCropBox().getWidth() - (y * (-1)); } else if (pageRotation == 180) { x = page.findCropBox().getWidth() + x; y = page.findCropBox().getHeight() - (y * (-1)); } else if (pageRotation == 270) { x = page.findCropBox().getHeight() + x; }/* w w w. j a v a2s . c om*/ String posString = "p:" + currentPage + ";x:" + x + ";y:" + y + ";w:" + w; logger.debug("Found Placeholder at: {}", posString); try { data.setTablePos(new TablePos(posString)); data.setPlaceholderName(objectName.getName()); placeholders.add(data); } catch (PdfAsException e) { throw new WrappedIOException(e); } } } catch (NoninvertibleTransformException e) { throw new WrappedIOException(e); } } } else { super.processOperator(operator, arguments); } }
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.placeholder.SignaturePlaceholderExtractor.java
License:EUPL
@Override protected void processOperator(Operator operator, List<COSBase> arguments) throws IOException { String operation = operator.getName(); if (operation.equals("Do")) { COSName objectName = (COSName) arguments.get(0); PDXObject xobject = (PDXObject) getResources().getXObject(objectName); if (xobject instanceof PDImageXObject) { try { PDImageXObject image = (PDImageXObject) xobject; SignaturePlaceholderData data = checkImage(image); if (data != null) { PDPage page = getCurrentPage(); Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); int pageRotation = page.getRotation(); pageRotation = pageRotation % 360; double rotationInRadians = Math.toRadians(pageRotation);//(page.findRotation() * Math.PI) / 180; AffineTransform rotation = new AffineTransform(); rotation.setToRotation(rotationInRadians); AffineTransform rotationInverse = rotation.createInverse(); Matrix rotationInverseMatrix = new Matrix(); rotationInverseMatrix.setFromAffineTransform(rotationInverse); Matrix rotationMatrix = new Matrix(); rotationMatrix.setFromAffineTransform(rotation); Matrix unrotatedCTM = ctm.multiply(rotationInverseMatrix); float x = unrotatedCTM.getXPosition(); float yPos = unrotatedCTM.getYPosition(); float yScale = unrotatedCTM.getScaleY(); float y = yPos + yScale; float w = unrotatedCTM.getScaleX(); ;//from w ww .ja v a2 s. co m logger.debug("Page height: {}", page.getCropBox().getHeight()); logger.debug("Page width: {}", page.getCropBox().getWidth()); if (pageRotation == 90) { y = page.getCropBox().getWidth() - (y * (-1)); } else if (pageRotation == 180) { x = page.getCropBox().getWidth() + x; y = page.getCropBox().getHeight() - (y * (-1)); } else if (pageRotation == 270) { x = page.getCropBox().getHeight() + x; } String posString = "p:" + currentPage + ";x:" + x + ";y:" + y + ";w:" + w; logger.debug("Found Placeholder at: {}", posString); try { data.setTablePos(new TablePos(posString)); data.setPlaceholderName(objectName.getName()); placeholders.add(data); } catch (PdfAsException e) { throw new IOException(); } } } catch (NoninvertibleTransformException e) { throw new IOException(e); } } } else { super.processOperator(operator, arguments); } }
From source file:chiliad.parser.pdf.extractor.vectorgraphics.operator.BeginInlineImage.java
License:Apache License
/** * process : BI : begin inline image./*from ww w . jav a2s . c om*/ * * @param operator The operator that is being executed. * @param arguments List * @throws IOException If there is an error displaying the inline image. */ @Override public void process(PDFOperator operator, List<COSBase> arguments) throws IOException { VectorGraphicsExtractor extractor = (VectorGraphicsExtractor) context; PDPage page = extractor.getPage(); //begin inline image object ImageParameters params = operator.getImageParameters(); PDInlinedImage image = new PDInlinedImage(); image.setImageParameters(params); image.setImageData(operator.getImageData()); if (params.isStencil()) { //TODO implement inline image stencil masks LOG.warn("Stencil masks are not implemented, background may be incorrect"); } BufferedImage awtImage = image.createImage(context.getColorSpaces()); if (awtImage == null) { LOG.warn("BeginInlineImage.process(): createImage returned NULL"); return; } int imageWidth = awtImage.getWidth(); int imageHeight = awtImage.getHeight(); double pageHeight = extractor.getPageSize().getHeight(); Matrix ctm = extractor.getGraphicsState().getCurrentTransformationMatrix(); int pageRotation = page.findRotation(); AffineTransform ctmAT = ctm.createAffineTransform(); ctmAT.scale(1f / imageWidth, 1f / imageHeight); Matrix rotationMatrix = new Matrix(); rotationMatrix.setFromAffineTransform(ctmAT); // calculate the inverse rotation angle // scaleX = m00 = cos // shearX = m01 = -sin // tan = sin/cos double angle = Math.atan(ctmAT.getShearX() / ctmAT.getScaleX()); Matrix translationMatrix = null; if (pageRotation == 0 || pageRotation == 180) { translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getXScale()), (float) (pageHeight - 2 * ctm.getYPosition() - Math.cos(angle) * ctm.getYScale())); } else if (pageRotation == 90 || pageRotation == 270) { translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getYScale()), (float) (pageHeight - 2 * ctm.getYPosition())); } rotationMatrix = rotationMatrix.multiply(translationMatrix); rotationMatrix.setValue(0, 1, (-1) * rotationMatrix.getValue(0, 1)); rotationMatrix.setValue(1, 0, (-1) * rotationMatrix.getValue(1, 0)); AffineTransform at = new AffineTransform(rotationMatrix.getValue(0, 0), rotationMatrix.getValue(0, 1), rotationMatrix.getValue(1, 0), rotationMatrix.getValue(1, 1), rotationMatrix.getValue(2, 0), rotationMatrix.getValue(2, 1)); extractor.drawImage(awtImage, at); }
From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawer.java
License:Apache License
@Override public void drawText(AttributedCharacterIterator iterator, IFontTextDrawerEnv env) throws IOException, FontFormatException { PDPageContentStream contentStream = env.getContentStream(); contentStream.beginText();/*from www . j a v a 2 s.c o m*/ Matrix textMatrix = new Matrix(); textMatrix.scale(1, -1); contentStream.setTextMatrix(textMatrix); StringBuilder sb = new StringBuilder(); boolean run = true; while (run) { Font attributeFont = (Font) iterator.getAttribute(TextAttribute.FONT); if (attributeFont == null) attributeFont = env.getFont(); Number fontSize = ((Number) iterator.getAttribute(TextAttribute.SIZE)); if (fontSize != null) attributeFont = attributeFont.deriveFont(fontSize.floatValue()); PDFont font = applyFont(attributeFont, env); Paint paint = (Paint) iterator.getAttribute(TextAttribute.FOREGROUND); if (paint == null) paint = env.getPaint(); /* * Apply the paint */ env.applyPaint(paint); boolean isStrikeThrough = TextAttribute.STRIKETHROUGH_ON .equals(iterator.getAttribute(TextAttribute.STRIKETHROUGH)); boolean isUnderline = TextAttribute.UNDERLINE_ON.equals(iterator.getAttribute(TextAttribute.UNDERLINE)); boolean isLigatures = TextAttribute.LIGATURES_ON.equals(iterator.getAttribute(TextAttribute.LIGATURES)); run = iterateRun(iterator, sb); String text = sb.toString(); /* * If we force the text write we may encounter situations where the font can not * display the characters. PDFBox will throw an exception in this case. We will * just silently ignore the text and not display it instead. */ try { showTextOnStream(env, contentStream, attributeFont, font, isStrikeThrough, isUnderline, isLigatures, text); } catch (IllegalArgumentException e) { if (font instanceof PDType1Font && !font.isEmbedded()) { /* * We tried to use a builtin default font, but it does not have the needed * characters. So we use a embedded font as fallback. */ try { if (fallbackFontUnknownEncodings == null) fallbackFontUnknownEncodings = findFallbackFont(env); if (fallbackFontUnknownEncodings != null) { env.getContentStream().setFont(fallbackFontUnknownEncodings, attributeFont.getSize2D()); showTextOnStream(env, contentStream, attributeFont, fallbackFontUnknownEncodings, isStrikeThrough, isUnderline, isLigatures, text); e = null; } } catch (IllegalArgumentException e1) { e = e1; } } if (e != null) System.err.println("PDFBoxGraphics: Can not map text " + text + " with font " + attributeFont.getFontName() + ": " + e.getMessage()); } } contentStream.endText(); }
From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DTestBase.java
License:Apache License
@SuppressWarnings("SpellCheckingInspection") void exportGraphic(String dir, String name, GraphicsExporter exporter) { try {//from w w w .jav a 2s .co m PDDocument document = new PDDocument(); PDFont pdArial = PDFontFactory.createDefaultFont(); File parentDir = new File("target/test/" + dir); // noinspection ResultOfMethodCallIgnored parentDir.mkdirs(); BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D imageGraphics = image.createGraphics(); exporter.draw(imageGraphics); imageGraphics.dispose(); ImageIO.write(image, "PNG", new File(parentDir, name + ".png")); for (Mode m : Mode.values()) { PDPage page = new PDPage(PDRectangle.A4); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400); PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null; contentStream.beginText(); contentStream.setStrokingColor(0, 0, 0); contentStream.setNonStrokingColor(0, 0, 0); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15); contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800)); contentStream.showText("Mode " + m); contentStream.endText(); switch (m) { case FontTextIfPossible: fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer(); registerFots(fontTextDrawer); break; case DefaultFontText: { fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts(); registerFots(fontTextDrawer); break; } case ForceFontText: fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer(); registerFots(fontTextDrawer); fontTextDrawer.registerFont("Arial", pdArial); break; case DefaultVectorized: default: break; } if (fontTextDrawer != null) { pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer); } exporter.draw(pdfBoxGraphics2D); pdfBoxGraphics2D.dispose(); PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject(); Matrix matrix = new Matrix(); matrix.translate(0, 20); contentStream.transform(matrix); contentStream.drawForm(appearanceStream); matrix.scale(1.5f, 1.5f); matrix.translate(0, 100); contentStream.transform(matrix); contentStream.drawForm(appearanceStream); contentStream.close(); } document.save(new File(parentDir, name + ".pdf")); document.close(); } catch (Exception e) { throw new RuntimeException(e); } }