List of usage examples for com.itextpdf.text.pdf PdfContentByte getEffectiveStringWidth
public float getEffectiveStringWidth(final String text, final boolean kerned)
From source file:com.github.ossdevs.jhocr.converter.HocrPageProcessor.java
License:Open Source License
/** * TODO describe this method.//from www . j a v a 2 s . c o m * * @param cb here the character spacing will be processed. * @param hocrWord will be used to process the {@link PdfContentByte}. * @param wordWidthPt will be used to process the {@link PdfContentByte}. */ private static void processHocrWordCharacterSpacing(PdfContentByte cb, HocrWord hocrWord, float wordWidthPt) { float charSpacing = 0; cb.setCharacterSpacing(charSpacing); float textWidthPt = cb.getEffectiveStringWidth(hocrWord.getText(), false); logger.debug("hocrWord: " + hocrWord.getId()); logger.debug("box width: " + wordWidthPt); logger.debug("text width: " + textWidthPt); if (textWidthPt > wordWidthPt) { while (textWidthPt > wordWidthPt) { charSpacing -= 0.05f; cb.setCharacterSpacing(charSpacing); float newTextWidthPt = cb.getEffectiveStringWidth(hocrWord.getText(), false); // !!! deadlock /** * TODO {@author Pablo} please confirm &/ describe the bug (deadlock) */ if (newTextWidthPt == textWidthPt || charSpacing > -0.5f) { break; } else { textWidthPt = newTextWidthPt; } } } }
From source file:de.jost_net.JVerein.io.FormularAufbereitung.java
License:Open Source License
private void goFormularfeld(PdfContentByte contentByte, Formularfeld feld, Object val) throws DocumentException, IOException { BaseFont bf = null;/* w w w . j a va2 s . com*/ if (feld.getFont().startsWith("FreeSans")) { String filename = "/fonts/FreeSans"; if (feld.getFont().length() > 8) { filename += feld.getFont().substring(9); } bf = BaseFont.createFont(filename + ".ttf", BaseFont.IDENTITY_H, true); } else { bf = BaseFont.createFont(feld.getFont(), BaseFont.CP1250, false); } float x = mm2point(feld.getX().floatValue()); float y = mm2point(feld.getY().floatValue()); if (val == null) { return; } buendig = links; String stringVal = getString(val); stringVal = stringVal.replace("\\n", "\n"); stringVal = stringVal.replaceAll("\r\n", "\n"); String[] ss = stringVal.split("\n"); for (String s : ss) { contentByte.setFontAndSize(bf, feld.getFontsize().floatValue()); contentByte.beginText(); float offset = 0; if (buendig == rechts) { offset = contentByte.getEffectiveStringWidth(s, true); } contentByte.moveText(x - offset, y); contentByte.showText(s); contentByte.endText(); y -= feld.getFontsize().floatValue() + 3; } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Writes text watermark to one of the 5 preconfigured locations * // w ww .j av a 2 s . co m * @param pcb * @param r * @param tokens * @param size * @param position */ private void writeAlignedText(PdfContentByte pcb, Rectangle r, Vector<String> tokens, float size, String position) { // get the dimensions of our 'rectangle' for text float height = size * tokens.size(); float width = 0; float centerX = 0, startY = 0; for (int i = 0; i < tokens.size(); i++) { if (pcb.getEffectiveStringWidth(tokens.get(i), false) > width) { width = pcb.getEffectiveStringWidth(tokens.get(i), false); } } // now that we have the width and height, we can calculate the center // position for // the rectangle that will contain our text. if (position.equals(POSITION_BOTTOMLEFT)) { centerX = width / 2 + PAD; startY = 0 + PAD + height; } else if (position.equals(POSITION_BOTTOMRIGHT)) { centerX = r.getWidth() - (width / 2) - PAD; startY = 0 + PAD + height; } else if (position.equals(POSITION_TOPLEFT)) { centerX = width / 2 + PAD; startY = r.getHeight() - (PAD * 2); } else if (position.equals(POSITION_TOPRIGHT)) { centerX = r.getWidth() - (width / 2) - PAD; startY = r.getHeight() - (PAD * 2); } else if (position.equals(POSITION_CENTER)) { centerX = r.getWidth() / 2; startY = (r.getHeight() / 2) + (height / 2); } // apply text to PDF pcb.beginText(); for (int t = 0; t < tokens.size(); t++) { pcb.showTextAligned(PdfContentByte.ALIGN_CENTER, tokens.get(t), centerX, startY - (size * t), 0); } pcb.endText(); }
From source file:org.javad.pdf.TitlePageContent.java
License:Apache License
@Override public OutputBounds generate(PdfContentByte content) { if (isSkipped()) { return new OutputBounds(getX(), getY(), 0, 0); }//from w ww.j a v a 2 s . c o m int maxWidth = 0; float top = getY() - PdfUtil.convertFromMillimeters( (configuration.getHeight() - configuration.getMarginBottom() - configuration.getMarginTop()) / 2); if (getImage() != null) { try { com.itextpdf.text.Image img = determineScaledImage(getImage()); if (img != null) { content.addImage(img); top = img.getAbsoluteY() - PdfUtil.convertFromMillimeters(25.0f); } } catch (Exception e) { logger.log(Level.FINER, "An error occured scaling the image. ", e); } } content.setColorStroke(BaseColor.BLACK); Font f = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumTitle); content.setFontAndSize(f.getBaseFont(), f.getSize()); content.setHorizontalScaling(110.0f); if (getTitle() != null && !getTitle().isEmpty()) { maxWidth = (int) f.getBaseFont().getWidthPoint(getTitle().toUpperCase(), f.getSize()); PdfUtil.renderConstrainedText(content, getTitle().toUpperCase(), f, getX(), top, maxWidth); } if (getSubTitle() != null && !getSubTitle().isEmpty()) { Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumSubtitle); top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(3.0f); content.setFontAndSize(subFont.getBaseFont(), subFont.getSize()); maxWidth = Math.max(maxWidth, (int) content.getEffectiveStringWidth(getSubTitle().toUpperCase(), false)); PdfUtil.renderConstrainedText(content, getSubTitle().toUpperCase(), subFont, getX(), top, maxWidth); } if (getDescription() != null && !getDescription().isEmpty()) { Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumDescription); top -= PdfUtil.convertFromMillimeters(15.0f); float width = PdfUtil.convertFromMillimeters( (configuration.getWidth() - configuration.getMarginLeft() - configuration.getMarginRight()) / 2); content.setFontAndSize(subFont.getBaseFont(), subFont.getSize()); top += PdfUtil.renderConstrainedText(content, getDescription(), subFont, width + PdfUtil.convertFromMillimeters(configuration.getMarginLeft()), top, (int) (width * 0.7f)); } if (!getItems().isEmpty()) { Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumContents); top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(6.0f); content.setFontAndSize(subFont.getBaseFont(), subFont.getSize()); for (String s : getItems()) { maxWidth = Math.max(maxWidth, (int) subFont.getBaseFont().getWidthPoint(s, subFont.getSize())); PdfUtil.renderConstrainedText(content, s, subFont, getX(), top, maxWidth); top -= PdfUtil.convertFromMillimeters(3.0f); } } content.setHorizontalScaling(100.0f); OutputBounds rect = new OutputBounds(getX() - maxWidth / 2, getY(), maxWidth, getY() - top); return rect; }
From source file:org.javad.pdf.util.PdfUtil.java
License:Apache License
protected static void improveRenderText(PdfContentByte content, String str, Font f, float x, float y) { BaseFont bf = f.getCalculatedBaseFont(false); if (i18Font == null && (System.currentTimeMillis() - LAST_CHECK_TIME > 10000)) { i18Font = FontRegistry.getInstance().getFont(PdfFontDefinition.ExtendedCharacters) .getCalculatedBaseFont(false); LAST_CHECK_TIME = System.currentTimeMillis(); }//from w ww . j a v a 2s.c o m StringBuilder buf = new StringBuilder(str.length()); boolean extendedCodePoint = false; float effWidth = 0.0f; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); int codePoint = Character.codePointAt("" + c, 0); boolean curCodePoint = (!bf.charExists(codePoint)) ? true : false; if (curCodePoint != extendedCodePoint) { content.setFontAndSize((extendedCodePoint) ? i18Font : bf, f.getSize()); effWidth += content.getEffectiveStringWidth(buf.toString(), false); buf = new StringBuilder(); extendedCodePoint = curCodePoint; } buf.append(c); } content.setFontAndSize(bf, f.getSize()); effWidth += content.getEffectiveStringWidth(buf.toString(), false); float x_pos = x - (effWidth / 2.0f); // eq. to showTextAligned content.beginText(); content.setTextMatrix(x_pos, y); BaseFont lastFont = bf; @SuppressWarnings("UnusedAssignment") BaseFont currentFont = lastFont; buf = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); int codePoint = Character.codePointAt("" + c, 0); if (!bf.charExists(codePoint)) { currentFont = i18Font; } else { currentFont = bf; } if (currentFont != lastFont) { content.showText(buf.toString()); buf = new StringBuilder(); content.setFontAndSize(currentFont, f.getSize()); lastFont = currentFont; } buf.append(c); } if (buf.length() > 0) { content.showText(buf.toString()); } content.endText(); }
From source file:org.javad.stamp.pdf.CompositeRow.java
License:Apache License
@Override public OutputBounds generate(PdfContentByte content) { if (isSkipped()) { return new OutputBounds(getX(), getY(), 0, 0); }// w w w .j a v a 2 s . c om float maxHeight = 0.0f; float maxWidth = 0.0f; float top = getY(); if (getDescription() != null && !getDescription().isEmpty()) { content.setColorStroke(BaseColor.BLACK); Font descFont = FontRegistry.getInstance().getFont(PdfFontDefinition.CompositeSetDescription); content.setFontAndSize(descFont.getBaseFont(), descFont.getSize()); top -= descFont.getCalculatedSize(); int count = 0; int tc = getDescription().split("\n").length; for (String desc : getDescription().split("\n")) { maxWidth = Math.max(maxWidth, content.getEffectiveStringWidth(desc, false)); PdfUtil.renderConstrainedText(content, desc, descFont, getX(), top, (int) maxWidth); count++; top -= descFont.getCalculatedSize() + ((count < tc) ? 2 : 4); } } float totalWidth = 0.0f; float totalHeight = getY() - top; float spacing = PdfUtil.convertFromMillimeters(getSpacingMode().getSpacing(box_spacing)); int count = 0; for (int i = 0; i < rows.size(); i++) { StampRow set = rows.get(i); if (set.isSkipped()) { continue; } totalWidth += PdfUtil.findMaximumWidth(set, content) + ((count > 0) ? spacing : 0.0f); count++; } float cur_x = getX() - totalWidth / 2.0f; count = 0; for (StampRow set : rows) { if (set.isSkipped()) { continue; } set.setX(cur_x + PdfUtil.findMaximumWidth(set, content) / 2.0f); set.setY(top); OutputBounds rect = set.generate(content); count++; cur_x += rect.width + ((count > 0) ? spacing : 0); maxHeight = Math.max(maxHeight, rect.height); } maxWidth = Math.max(maxWidth, totalWidth); totalHeight += maxHeight; return new OutputBounds(getX() - (maxWidth / 2.0f), getY(), maxWidth, totalHeight); }
From source file:org.javad.stamp.pdf.StampSet.java
License:Apache License
@Override public OutputBounds generate(PdfContentByte content) { if (isSkipped()) { return new OutputBounds(getX(), getY(), 0, 0); }//from ww w.ja va2s . c o m float maxWidth = 0; content.setColorStroke(BaseColor.BLACK); float top = getY(); if (getIssue() != null && !getIssue().isEmpty()) { top -= PdfUtil.convertFromMillimeters(5.0f); Font f = FontRegistry.getInstance().getFont(PdfFontDefinition.SetIssue); content.setFontAndSize(f.getBaseFont(), f.getSize()); String is = getIssue().replace("\\n", "\n"); StringTokenizer tokenizer = new StringTokenizer(is, "\n", true); while (tokenizer.hasMoreTokens()) { is = tokenizer.nextToken(); maxWidth = Math.max(maxWidth, content.getEffectiveStringWidth(is, false)); if (is.equals("\n")) { top -= f.getCalculatedSize() + 2; } else { PdfUtil.renderConstrainedText(content, is, f, getX(), top, (int) maxWidth); if (tokenizer.hasMoreTokens()) { top -= f.getCalculatedSize() + 2; } } } top -= PdfUtil.convertFromMillimeters(3.0f); } if (getDescription() != null && !getDescription().isEmpty()) { Font descFont = FontRegistry.getInstance().getFont(PdfFontDefinition.SetDescription); content.setFontAndSize(descFont.getBaseFont(), descFont.getSize()); top -= descFont.getCalculatedSize(); int count = 0; int tc = getDescription().split("\n").length; for (String desc : getDescription().split("\n")) { maxWidth = Math.max(maxWidth, content.getEffectiveStringWidth(desc, false)); PdfUtil.renderConstrainedText(content, desc, descFont, getX(), top, (int) maxWidth); count++; if (count < tc) { top -= descFont.getCalculatedSize() + 2; } } } if (getDescriptionSecondary() != null && !getDescriptionSecondary().isEmpty()) { Font secFont = FontRegistry.getInstance().getFont(PdfFontDefinition.SetDescriptionSecondary); content.setFontAndSize(secFont.getBaseFont(), secFont.getSize()); top -= secFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(3.0f); int count = 0; int tc = getDescriptionSecondary().split("\n").length; for (String desc : getDescriptionSecondary().split("\n")) { maxWidth = Math.max(maxWidth, content.getEffectiveStringWidth(desc, false)); PdfUtil.renderConstrainedText(content, desc, secFont, getX(), top, (int) maxWidth); count++; if (count < tc) { top -= secFont.getCalculatedSize() + 2; } } } if (!rows.isEmpty()) { top -= ((top != getY()) ? PdfUtil.convertFromMillimeters(3.0f) : 0); int count = 0; for (int i = 0; i < rows.size(); i++) { ISetContent row = rows.get(i); if (row.isSkipped()) { continue; } top -= ((count > 0) ? (PdfUtil.convertFromMillimeters(verticalPadding)) : 0.0f); row.setX(getX()); row.setY(top); OutputBounds bounds = row.generate(content); count++; top -= bounds.height; maxWidth = Math.max(maxWidth, bounds.width); } } if (getComment() != null && !getComment().isEmpty()) { top -= PdfUtil.convertFromMillimeters((int) (0.75 * verticalPadding)); Font cFont = FontRegistry.getInstance().getFont(PdfFontDefinition.SetComment); content.setFontAndSize(cFont.getBaseFont(), cFont.getSize()); for (String s : getComment().split("\n")) { top -= cFont.getCalculatedSize(); maxWidth = Math.max(maxWidth, content.getEffectiveStringWidth(s, false)); PdfUtil.renderConstrainedText(content, s, cFont, getX(), top, (int) maxWidth); } } OutputBounds rect = new OutputBounds(getX() - maxWidth / 2, getY(), maxWidth, getY() - top); return rect; }
From source file:pl.marcinmilkowski.hocrtopdf.Main.java
License:Open Source License
/** * @param args/* w ww. java 2 s .com*/ */ public static void main(String[] args) { try { if (args.length < 1 || args[0] == "--help" || args[0] == "-h") { System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n" + "\n" + "Converts hOCR files into PDF\n" + "\n" + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n"); if (args.length < 1) System.exit(-1); else System.exit(0); } URL inputHOCRFile = null; FileOutputStream outputPDFStream = null; try { File file = new File(args[0]); inputHOCRFile = file.toURI().toURL(); } catch (MalformedURLException e) { System.out.println("The first parameter has to be a valid file."); System.out.println("We got an error: " + e.getMessage()); System.exit(-1); } try { outputPDFStream = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { System.out.println("The second parameter has to be a valid URL"); System.exit(-1); } // The resolution of a PDF file (using iText) is 72pt per inch float pointsPerInch = 72.0f; // Using the jericho library to parse the HTML file Source source = new Source(inputHOCRFile); int pageCounter = 1; Document pdfDocument = null; PdfWriter pdfWriter = null; PdfContentByte cb = null; RandomAccessFileOrArray ra = null; // Find the tag of class ocr_page in order to load the scanned image StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE); while (pageTag != null) { int prevPos = pageTag.getEnd(); Pattern imagePattern = Pattern.compile("image\\s+([^;]+)"); Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title")); if (!imageMatcher.find()) { System.out.println("Could not find a tag of class \"ocr_page\", aborting."); System.exit(-1); } // Load the image Image pageImage = null; try { File file = new File(imageMatcher.group(1)); pageImage = Image.getInstance(file.toURI().toURL()); } catch (MalformedURLException e) { System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1) + ", aborting."); System.exit(-1); } if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might // be // multipage // tiff! File file = new File(imageMatcher.group(1)); if (pageCounter == 1 || ra == null) { ra = new RandomAccessFileOrArray(file.toURI().toURL()); } int nPages = TiffImage.getNumberOfPages(ra); if (nPages > 0 && pageCounter <= nPages) { pageImage = TiffImage.getTiffImage(ra, pageCounter); } } int dpiX = pageImage.getDpiX(); if (dpiX == 0) { // for images that don't set the resolution we assume // 300 dpi dpiX = 300; } int dpiY = pageImage.getDpiY(); if (dpiY == 0) { // as above for dpiX dpiY = 300; } float dotsPerPointX = dpiX / pointsPerInch; float dotsPerPointY = dpiY / pointsPerInch; float pageImagePixelHeight = pageImage.getHeight(); if (pdfDocument == null) { pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY)); pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream); pdfDocument.open(); // Put the text behind the picture (reverse for debugging) // cb = pdfWriter.getDirectContentUnder(); cb = pdfWriter.getDirectContent(); } else { pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY)); pdfDocument.newPage(); } // first define a standard font for our text BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED); Font defaultFont = new Font(base, 8); // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, // CMYKColor.BLACK); cb.setHorizontalScaling(1.0f); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Put the image in front of the text (reverse for debugging) // pdfWriter.getDirectContent().addImage(pageImage); pdfWriter.getDirectContentUnder().addImage(pageImage); // In order to place text behind the recognised text snippets we are // interested in the bbox property Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}"); // This pattern separates the coordinates of the bbox property Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)"); // Only tags of the ocr_line class are interesting StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE); while (ocrTag != null) { prevPos = ocrTag.getEnd(); if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) { net.htmlparser.jericho.Element lineElement = ocrTag.getElement(); Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title")); if (bboxMatcher.find()) { // We found a tag of the ocr_line class containing a bbox property Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group()); bboxCoordinateMatcher.find(); int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))), Integer.parseInt((bboxCoordinateMatcher.group(2))), Integer.parseInt((bboxCoordinateMatcher.group(3))), Integer.parseInt((bboxCoordinateMatcher.group(4))) }; String line = lineElement.getContent().getTextExtractor().toString(); float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; // Put the text into the PDF cb.beginText(); // Comment the next line to debug the PDF output (visible Text) cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); // height cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1)); // width cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false)); cb.moveText((coordinates[0] / dotsPerPointX), ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY)); cb.showText(line); cb.endText(); cb.setHorizontalScaling(1.0f); } } else { if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) { pageCounter++; pageTag = ocrTag; break; } } ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE); } if (ocrTag == null) { pdfDocument.close(); break; } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }