List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getWidth
public float getWidth()
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
/** * Creates a stream (from FOP's PDF library) from a PDF page parsed with PDFBox. * @param sourceDoc the source PDF the given page to be copied belongs to * @param page the page to transform into a stream * @param key value to use as key for the stream * @param atdoc adjustment for stream//from www. ja va2 s . c o m * @param fontinfo fonts * @param pos rectangle * @return the stream * @throws IOException if an I/O error occurs */ public String createStreamFromPDFBoxPage(PDDocument sourceDoc, PDPage page, String key, AffineTransform atdoc, FontInfo fontinfo, Rectangle pos) throws IOException { handleAnnotations(sourceDoc, page, atdoc); if (pageNumbers.containsKey(targetPage.getPageIndex())) { pageNumbers.get(targetPage.getPageIndex()).set(0, targetPage.makeReference()); } PDResources sourcePageResources = page.getResources(); PDStream pdStream = getContents(page); COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT); COSDictionary fontsBackup = null; UniqueName uniqueName = new UniqueName(key, sourcePageResources); String newStream = null; if (fonts != null && pdfDoc.isMergeFontsEnabled()) { fontsBackup = new COSDictionary(fonts); MergeFontsPDFWriter m = new MergeFontsPDFWriter(fonts, fontinfo, uniqueName, parentFonts, currentMCID); newStream = m.writeText(pdStream); // if (newStream != null) { // for (Object f : fonts.keySet().toArray()) { // COSDictionary fontdata = (COSDictionary)fonts.getDictionaryObject((COSName)f); // if (getUniqueFontName(fontdata) != null) { // fonts.removeItem((COSName)f); // } // } // } } if (newStream == null) { PDFWriter writer = new PDFWriter(uniqueName, currentMCID); newStream = writer.writeText(pdStream); currentMCID = writer.getCurrentMCID(); } pdStream = new PDStream(sourceDoc, new ByteArrayInputStream(newStream.getBytes("ISO-8859-1"))); mergeXObj(sourcePageResources.getCOSObject(), fontinfo, uniqueName); PDFDictionary pageResources = (PDFDictionary) cloneForNewDocument(sourcePageResources.getCOSObject()); PDFDictionary fontDict = (PDFDictionary) pageResources.get("Font"); if (fontDict != null && pdfDoc.isMergeFontsEnabled()) { for (Map.Entry<String, Typeface> fontEntry : fontinfo.getUsedFonts().entrySet()) { Typeface font = fontEntry.getValue(); if (font instanceof FOPPDFFont) { FOPPDFFont pdfFont = (FOPPDFFont) font; if (pdfFont.getRef() == null) { pdfFont.setRef(new PDFDictionary()); pdfDoc.assignObjectNumber(pdfFont.getRef()); } fontDict.put(fontEntry.getKey(), pdfFont.getRef()); } } } updateXObj(sourcePageResources.getCOSObject(), pageResources); if (fontsBackup != null) { sourcePageResources.getCOSObject().setItem(COSName.FONT, fontsBackup); } COSStream originalPageContents = pdStream.getCOSObject(); bindOptionalContent(sourceDoc); PDFStream pageStream; Set filter; // if (originalPageContents instanceof COSStreamArray) { // COSStreamArray array = (COSStreamArray)originalPageContents; // pageStream = new PDFStream(); // InputStream in = array.getUnfilteredStream(); // OutputStream out = pageStream.getBufferOutputStream(); // IOUtils.copyLarge(in, out); // filter = FILTER_FILTER; // } else { pageStream = (PDFStream) cloneForNewDocument(originalPageContents); filter = Collections.EMPTY_SET; // } if (pageStream == null) { pageStream = new PDFStream(); } if (originalPageContents != null) { transferDict(originalPageContents, pageStream, filter); } transferPageDict(fonts, uniqueName, sourcePageResources); PDRectangle mediaBox = page.getMediaBox(); PDRectangle cropBox = page.getCropBox(); PDRectangle viewBox = cropBox != null ? cropBox : mediaBox; //Handle the /Rotation entry on the page dict int rotation = PDFUtil.getNormalizedRotation(page); //Transform to FOP's user space float w = (float) pos.getWidth() / 1000f; float h = (float) pos.getHeight() / 1000f; if (rotation == 90 || rotation == 270) { float tmp = w; w = h; h = tmp; } atdoc.setTransform(AffineTransform.getScaleInstance(w / viewBox.getWidth(), h / viewBox.getHeight())); atdoc.translate(0, viewBox.getHeight()); atdoc.rotate(-Math.PI); atdoc.scale(-1, 1); atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY()); rotate(rotation, viewBox, atdoc); StringBuilder boxStr = new StringBuilder(); boxStr.append(PDFNumber.doubleOut(mediaBox.getLowerLeftX())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getLowerLeftY())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getWidth())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getHeight())).append(" re W n\n"); return boxStr.toString() + IOUtils.toString(pdStream.createInputStream(null), "ISO-8859-1"); }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
private void rotate(int rotation, PDRectangle viewBox, AffineTransform atdoc) { float x = viewBox.getWidth() + viewBox.getLowerLeftX(); float y = viewBox.getHeight() + viewBox.getLowerLeftY(); switch (rotation) { case 90:/*from w w w. jav a 2s .c o m*/ atdoc.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth()); atdoc.translate(0, viewBox.getWidth()); atdoc.rotate(-Math.PI / 2.0); atdoc.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth()); break; case 180: atdoc.translate(x, y); atdoc.rotate(-Math.PI); atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY()); break; case 270: atdoc.translate(viewBox.getLowerLeftX(), y); atdoc.rotate(Math.toRadians(270 + 180)); atdoc.translate(-x, -y); break; default: //no additional transformations necessary break; } }
From source file:org.apache.fop.render.pdf.pdfbox.PreloaderPDF.java
License:Apache License
private ImageInfo loadPDF(String uri, Source src, ImageContext context) throws IOException, ImageException { int selectedPage = ImageUtil.needPageIndexFromURI(uri); URI docURI = deriveDocumentURI(src.getSystemId()); PDDocument pddoc = getDocument(context, docURI, src); pddoc = Interceptors.getInstance().interceptOnLoad(pddoc, docURI); //Disable the warning about a missing close since we rely on the GC to decide when //the cached PDF shall be disposed off. pddoc.getDocument().setWarnMissingClose(false); int pageCount = pddoc.getNumberOfPages(); if (selectedPage < 0 || selectedPage >= pageCount) { throw new ImageException("Selected page (index: " + selectedPage + ") does not exist in the PDF file. The document has " + pddoc.getNumberOfPages() + " pages."); }/*from w ww. ja va 2 s . c o m*/ PDPage page = pddoc.getDocumentCatalog().getPages().get(selectedPage); PDRectangle mediaBox = page.getMediaBox(); PDRectangle cropBox = page.getCropBox(); PDRectangle viewBox = cropBox != null ? cropBox : mediaBox; int w = Math.round(viewBox.getWidth() * 1000); int h = Math.round(viewBox.getHeight() * 1000); //Handle the /Rotation entry on the page dict int rotation = PDFUtil.getNormalizedRotation(page); if (rotation == 90 || rotation == 270) { //Swap width and height int exch = w; w = h; h = exch; } ImageSize size = new ImageSize(); size.setSizeInMillipoints(w, h); size.setResolution(context.getSourceResolution()); size.calcPixelsFromSize(); ImageInfo info = new ImageInfo(uri, ImagePDF.MIME_PDF); info.setSize(size); info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, new ImagePDF(info, pddoc)); int lastPageIndex = pddoc.getNumberOfPages() - 1; if (selectedPage < lastPageIndex) { info.getCustomObjects().put(ImageInfo.HAS_MORE_IMAGES, Boolean.TRUE); } return info; }
From source file:org.dspace.disseminate.CitationDocument.java
License:BSD License
public int drawStringWordWrap(PDPage page, PDPageContentStream contentStream, String text, int startX, int startY, PDFont pdfFont, float fontSize) throws IOException { float leading = 1.5f * fontSize; PDRectangle mediabox = page.findMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; List<String> lines = new ArrayList<>(); int lastSpace = -1; while (text.length() > 0) { int spaceIndex = text.indexOf(' ', lastSpace + 1); if (spaceIndex < 0) { lines.add(text);//from w w w. j a v a2s. c om text = ""; } else { String subString = text.substring(0, spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000; if (size > width) { if (lastSpace < 0) // So we have a word longer than the line... draw it anyways lastSpace = spaceIndex; subString = text.substring(0, lastSpace); lines.add(subString); text = text.substring(lastSpace).trim(); lastSpace = -1; } else { lastSpace = spaceIndex; } } } contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.moveTextPositionByAmount(startX, startY); int currentY = startY; for (String line : lines) { contentStream.drawString(line); currentY -= leading; contentStream.moveTextPositionByAmount(0, -leading); } contentStream.endText(); return currentY; }
From source file:org.dspace.disseminate.CitationDocumentServiceImpl.java
License:BSD License
@Override public int drawStringWordWrap(PDPage page, PDPageContentStream contentStream, String text, int startX, int startY, PDFont pdfFont, float fontSize) throws IOException { float leading = 1.5f * fontSize; PDRectangle mediabox = page.getMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; List<String> lines = new ArrayList<>(); int lastSpace = -1; while (text.length() > 0) { int spaceIndex = text.indexOf(' ', lastSpace + 1); if (spaceIndex < 0) { lines.add(text);//from ww w. jav a 2 s.co m text = ""; } else { String subString = text.substring(0, spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000; if (size > width) { if (lastSpace < 0) // So we have a word longer than the line... draw it anyways lastSpace = spaceIndex; subString = text.substring(0, lastSpace); lines.add(subString); text = text.substring(lastSpace).trim(); lastSpace = -1; } else { lastSpace = spaceIndex; } } } contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.moveTextPositionByAmount(startX, startY); int currentY = startY; for (String line : lines) { contentStream.drawString(line); currentY -= leading; contentStream.moveTextPositionByAmount(0, -leading); } contentStream.endText(); return currentY; }
From source file:org.elacin.pdfextract.datasource.pdfbox.PDFBoxIntegration.java
License:Apache License
/** * This will process the contents of a page. * * @param page The page to process./*from w w w .j a v a2 s . c om*/ * @param content The contents of the page. * @throws IOException If there is an error processing the page. */ protected void processPage(@NotNull PDPage page, COSStream content) throws IOException { if ((currentPageNo >= startPage) && (currentPageNo <= endPage)) { /* show which page we are working on in the log */ MDC.put("page", currentPageNo); charactersForPage.clear(); characterListMapping.clear(); pageSize = page.findCropBox().createDimension(); rotation = (float) page.findRotation(); /* this is used to 'draw' images on during pdf parsing */ graphicsDrawer.clearSurface(); setGraphicsState(null); resetEngine(); processStream(page, page.findResources(), content); filterOutBadFonts(charactersForPage); /* filter out remaining definite bad characters */ filterOutControlCodes(charactersForPage); List<PhysicalText> texts = new ArrayList<PhysicalText>(charactersForPage.size()); for (ETextPosition tp : charactersForPage) { texts.add(tp.convertText(fonts)); } final PDRectangle mediaBox = page.findMediaBox(); Rectangle dimensions = new Rectangle(mediaBox.getLowerLeftX(), mediaBox.getLowerLeftY(), mediaBox.getWidth(), mediaBox.getHeight()); PageContent thisPage = new PageContent(texts, graphicsDrawer.getGraphicContents(), currentPageNo, dimensions); docContent.addPage(thisPage); MDC.remove("page"); } }
From source file:org.esteco.jira.pdf.UsingTextMatrix.java
License:Apache License
/** * creates a sample document with some text using a text matrix. * * @param message The message to write in the file. * @param outfile The resulting PDF.//from w w w . ja va 2 s. c o m * @throws IOException If there is an error writing the data. */ public void doIt(String message, String outfile) throws IOException { // the document PDDocument doc = null; try { doc = new PDDocument(); // Page 1 PDFont font = PDType1Font.HELVETICA; PDPage page = new PDPage(PDRectangle.A4); doc.addPage(page); float fontSize = 12.0f; PDRectangle pageSize = page.getMediaBox(); float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f; float stringWidth = font.getStringWidth(message); float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f; PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // counterclockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextMatrix(Matrix.getRotateInstance(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition)); contentStream.showText(message + " " + i); } // clockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextMatrix( Matrix.getRotateInstance(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition)); contentStream.showText(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 2 page = new PDPage(PDRectangle.A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // text scaling and translation for (int i = 0; i < 10; i++) { contentStream.setTextMatrix(new Matrix(12 + (i * 6), 0, 0, 12 + (i * 6), 100, 100 + i * 50)); contentStream.showText(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 3 page = new PDPage(PDRectangle.A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); int i = 0; // text scaling combined with rotation contentStream.setTextMatrix(new Matrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.endText(); contentStream.close(); doc.save(outfile); } finally { if (doc != null) { doc.close(); } } }
From source file:org.fit.cssbox.pdf.CSSBoxTree.java
License:Open Source License
/** * Creates a style definition used for pages. * @return The page style definition.// w w w .j ava 2 s. c om */ protected NodeData createPageStyle() { NodeData ret = createBlockStyle(); TermFactory tf = CSSFactory.getTermFactory(); ret.push(createDeclaration("position", tf.createIdent("relative"))); ret.push(createDeclaration("border-width", tf.createLength(1f, Unit.px))); ret.push(createDeclaration("border-style", tf.createIdent("solid"))); ret.push(createDeclaration("border-color", tf.createColor(0, 0, 255))); ret.push(createDeclaration("margin", tf.createLength(0.5f, Unit.em))); PDRectangle layout = getCurrentMediaBox(); if (layout != null) { float w = layout.getWidth(); float h = layout.getHeight(); final int rot = pdpage.getRotation(); if (rot == 90 || rot == 270) { float x = w; w = h; h = x; } ret.push(createDeclaration("width", tf.createLength(w, unit))); ret.push(createDeclaration("height", tf.createLength(h, unit))); } else log.warn("No media box found"); return ret; }
From source file:org.fit.pdfdom.PDFBoxTree.java
License:Open Source License
protected AffineTransform createCurrentPageTransformation() { PDRectangle cb = pdpage.getCropBox(); AffineTransform pageTransform = new AffineTransform(); switch (pdpage.getRotation()) { case 90:// w w w . j ava 2 s . c o m pageTransform.translate(cb.getHeight(), 0); break; case 180: pageTransform.translate(cb.getWidth(), cb.getHeight()); break; case 270: pageTransform.translate(0, cb.getWidth()); break; } pageTransform.rotate(Math.toRadians(pdpage.getRotation())); pageTransform.translate(0, cb.getHeight()); pageTransform.scale(1, -1); pageTransform.translate(-cb.getLowerLeftX(), -cb.getLowerLeftY()); return pageTransform; }
From source file:org.fit.pdfdom.PDFDomTree.java
License:Open Source License
/** * Creates an element that represents a single page. * @return the resulting DOM element//w w w . j av a 2s. co m */ protected Element createPageElement() { String pstyle = ""; PDRectangle layout = getCurrentMediaBox(); if (layout != null) { /*System.out.println("x1 " + layout.getLowerLeftX()); System.out.println("y1 " + layout.getLowerLeftY()); System.out.println("x2 " + layout.getUpperRightX()); System.out.println("y2 " + layout.getUpperRightY()); System.out.println("rot " + pdpage.findRotation());*/ float w = layout.getWidth(); float h = layout.getHeight(); final int rot = pdpage.getRotation(); if (rot == 90 || rot == 270) { float x = w; w = h; h = x; } pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";"; pstyle += "overflow:hidden;"; } else log.warn("No media box found"); Element el = doc.createElement("div"); el.setAttribute("id", "page_" + (pagecnt++)); el.setAttribute("class", "page"); el.setAttribute("style", pstyle); return el; }