List of usage examples for org.apache.pdfbox.cos COSName FONT
COSName FONT
To view the source code for org.apache.pdfbox.cos COSName FONT.
Click Source Link
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox.placeholder.SignaturePlaceholderExtractor.java
License:EUPL
@Override public Map<String, PDFont> getFonts() { if (fonts == null) { // at least an empty map will be returned // TODO we should return null instead of an empty map fonts = new HashMap<String, PDFont>(); if (this.getResources() != null && this.getResources().getCOSDictionary() != null) { COSDictionary fontsDictionary = (COSDictionary) this.getResources().getCOSDictionary() .getDictionaryObject(COSName.FONT); if (fontsDictionary == null) { // ignore we do not want to set anything, never when creating a signature!!!!! //fontsDictionary = new COSDictionary(); //this.getResources().getCOSDictionary().setItem(COSName.FONT, fontsDictionary); } else { for (COSName fontName : fontsDictionary.keySet()) { COSBase font = fontsDictionary.getDictionaryObject(fontName); // data-000174.pdf contains a font that is a COSArray, looks to be an error in the // PDF, we will just ignore entries that are not dictionaries. if (font instanceof COSDictionary) { PDFont newFont = null; try { newFont = PDFontFactory.createFont((COSDictionary) font); } catch (IOException exception) { logger.error("error while creating a font", exception); }//from ww w .j av a 2 s . co m if (newFont != null) { fonts.put(fontName.getName(), newFont); } } } } } } return fonts; }
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.placeholder.SignaturePlaceholderExtractor.java
License:EUPL
public Map<String, PDFont> getFonts() { if (fonts == null) { // at least an empty map will be returned // TODO we should return null instead of an empty map fonts = new HashMap<String, PDFont>(); if (this.getResources() != null && this.getResources().getCOSObject() != null) { COSDictionary fontsDictionary = (COSDictionary) this.getResources().getCOSObject() .getDictionaryObject(COSName.FONT); if (fontsDictionary == null) { // ignore we do not want to set anything, never when creating a signature!!!!! //fontsDictionary = new COSDictionary(); //this.getResources().getCOSDictionary().setItem(COSName.FONT, fontsDictionary); } else { for (COSName fontName : fontsDictionary.keySet()) { COSBase font = fontsDictionary.getDictionaryObject(fontName); // data-000174.pdf contains a font that is a COSArray, looks to be an error in the // PDF, we will just ignore entries that are not dictionaries. if (font instanceof COSDictionary) { PDFont newFont = null; try { newFont = PDFontFactory.createFont((COSDictionary) font); } catch (IOException exception) { logger.error("error while creating a font", exception); }//from w w w .j av a 2 s .c om if (newFont != null) { fonts.put(fontName.getName(), newFont); } } } } } } return fonts; }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFBoxFont.java
License:EUPL
private PDFont findCachedFont(PDFBOXObject pdfObject, FontInfoCache fontInfo) { try {// w w w. j a v a 2 s . c om if (pdfObject.getFontCache().containsKey(fontInfo.fontPath)) { return pdfObject.getFontCache().get(fontInfo.fontPath); } List<COSObject> cosObjects = pdfObject.getDocument().getDocument().getObjectsByType(COSName.FONT); //COSName cosFontName = COSName.getPDFName(fontInfo.fontName); //COSName cosFontFamily = COSName.getPDFName(fontInfo.fontFamily); Iterator<COSObject> cosObjectIt = cosObjects.iterator(); while (cosObjectIt.hasNext()) { COSObject cosObject = cosObjectIt.next(); COSDictionary baseObject = (COSDictionary) cosObject.getObject(); if (baseObject instanceof COSDictionary) { COSDictionary fontDictionary = (COSDictionary) baseObject; COSBase subType = cosObject.getItem(COSName.SUBTYPE); COSDictionary fontDescriptor = (COSDictionary) cosObject.getDictionaryObject(COSName.FONT_DESC); if (fontDescriptor != null) { String fontName = fontDescriptor.getNameAsString(COSName.FONT_NAME); String fontFamily = fontDescriptor.getNameAsString(COSName.FONT_FAMILY); logger.trace("Inspecting Font {} - {}", fontFamily, fontName); if (COSName.TRUE_TYPE.equals(subType)) { if (fontInfo.fontName != null && fontInfo.fontName.equals(fontName) && fontInfo.fontFamily != null && fontInfo.fontFamily.equals(fontFamily)) { // Found it! :) logger.info("Found Font {}", fontInfo.fontName); return new PDTrueTypeFont(fontDictionary); } } else { logger.debug("Font not a TTF"); } } } else { logger.debug("Font not a COSDictionary"); } } } catch (Exception e) { logger.info("Failed to load existing TTF fonts!", e); } return null; }
From source file:at.knowcenter.wag.egov.egiz.pdf.PDFPage.java
License:EUPL
@Override public Map<String, PDFont> getFonts() { COSBase fontObj = null;//from ww w. j av a 2s .c o m if (getCurrentPage().getResources() != null && getCurrentPage().getResources().getCOSDictionary() != null && getCurrentPage().getResources().getCOSDictionary().getDictionaryObject(COSName.FONT) != null) { fontObj = getCurrentPage().getResources().getCOSDictionary().getDictionaryObject(COSName.FONT); } Map<String, PDFont> fontMap = getCurrentPage().findResources().getFonts(); if (fontObj != null) { getCurrentPage().getResources().getCOSDictionary().setItem(COSName.FONT, fontObj); } return fontMap; }
From source file:modules.PDFFontDependencyExtractorModule.java
License:Apache License
public PDFFontResults extractFontList(File f) throws IOException, InvalidParameterException { PDDocument document;//from w w w . j a v a 2s . c om try { document = PDDocument.load(f); } catch (IOException x) { throw new InvalidParameterException("Not a PDF file"); } SortedSet<FontInformation> ret = new TreeSet<FontInformation>(new Comparator<FontInformation>() { @Override public int compare(FontInformation o1, FontInformation o2) { int a = o1.fontName.compareTo(o2.fontName); if (a != 0) return a; else return o1.fontType.compareTo(o2.fontType); } }); document.getDocumentCatalog().getAllPages(); // The code down here is easier as it gets all the fonts used in the // document. Still, this would inlcude unused fonts, so we get the fonts // page by page and add them to a Hash table. for (COSObject c : document.getDocument().getObjectsByType(COSName.FONT)) { if (c == null || !(c.getObject() instanceof COSDictionary)) { continue; // System.out.println(c.getObject()); } COSDictionary fontDictionary = (COSDictionary) c.getObject(); // System.out.println(dic.getNameAsString(COSName.BASE_FONT)); // } // } // int pagen = document.getNumberOfPages(); // i=0; // for (int p=0;p<pagen;p++){ // PDPage page = (PDPage)pages.get(p); // PDResources res = page.findResources(); // //for each page resources // if (res==null) continue; // // get the font dictionary // COSDictionary fonts = (COSDictionary) // res.getCOSDictionary().getDictionaryObject( COSName.FONT ); // for( COSName fontName : fonts.keySet() ) { // COSObject font = (COSObject) fonts.getItem( fontName ); // // if the font has already been visited we ingore it // long objectId = font.getObjectNumber().longValue(); // if (ret.get(objectId)!=null) // continue; // if( font==null || ! (font.getObject() instanceof COSDictionary) ) // continue; // COSDictionary fontDictionary = (COSDictionary)font.getObject(); // Type MUSt be font if (!fontDictionary.getNameAsString(COSName.TYPE).equals("Font")) { continue; } // get the variables FontInformation fi = new FontInformation(); fi.fontType = fontDictionary.getNameAsString(COSName.SUBTYPE); String baseFont = fontDictionary.getNameAsString(COSName.BASE_FONT); if (baseFont == null) { continue; } if (Arrays.binarySearch(standard14, baseFont) >= 0) { continue; } COSDictionary fontDescriptor = (COSDictionary) fontDictionary.getDictionaryObject(COSName.FONT_DESC); COSBase enc = fontDictionary.getItem(COSName.ENCODING); COSBase uni = fontDictionary.getItem(COSName.TO_UNICODE); fontDictionary.getInt(COSName.FIRST_CHAR); fontDictionary.getInt(COSName.LAST_CHAR); String encoding; boolean toUnicode = uni != null; if (enc == null) { encoding = "standard14"; } if (enc instanceof COSString) { encoding = ((COSString) enc).getString(); } else { encoding = "table"; } fi.isSubset = false; boolean t = true; // Type one and TT can have subsets defineing the basename see 5.5.3 // pdfref 1.6 // if (fi.fontType.lastIndexOf(COSName.TYPE1.getName())!=-1 || // fi.fontType.equals(COSName.TRUE_TYPE.getName()) ) if (baseFont != null) { if (baseFont.length() > 6) { for (int k = 0; k < 6; k++) if (!Character.isUpperCase(baseFont.charAt(k))) { t = false; } if (baseFont.charAt(6) != '+') { t = false; } } else { t = false; } fi.isSubset = t; if (fi.isSubset) { fi.baseName = baseFont.substring(0, 6); baseFont = baseFont.substring(7); } } fi.fontFlags = 0; if (fi.fontType.equals(COSName.TYPE0.getName()) || fi.fontType.equals(COSName.TYPE3.getName())) { fi.isEmbedded = true; } if (fontDescriptor != null) { // in Type1 charset indicates font is subsetted if (fontDescriptor.getItem(COSName.CHAR_SET) != null) { fi.isSubset = true; } if (fontDescriptor.getItem(COSName.FONT_FILE) != null || fontDescriptor.getItem(COSName.FONT_FILE3) != null || fontDescriptor.getItem(COSName.FONT_FILE2) != null) { fi.isEmbedded = true; } fi.fontFlags = fontDescriptor.getInt(COSName.getPDFName("Flags")); fi.fontFamily = fontDescriptor.getString(COSName.FONT_FAMILY); fi.fontStretch = fontDescriptor.getString(COSName.FONT_STRETCH); } fi.charset = encoding; fi.fontName = baseFont; fi.isToUnicode = toUnicode; fi.encoding = fontDictionary.getNameAsString(COSName.CID_TO_GID_MAP); ret.add(fi); } // for all fonts HashMultimap<String, FontInformation> m = HashMultimap.create(); for (FontInformation ff : ret) { m.put(ff.fontName, ff); } LinkedList<FontInformation> missing = new LinkedList<FontInformation>(); Set<String> k = m.keySet(); for (String kk : k) { Set<FontInformation> s = m.get(kk); if (s.size() < 1) { continue; } if (s.size() > 1) { boolean found = false; FontInformation ff = null; for (FontInformation fonti : s) { if (!fonti.isEmbedded) { ff = fonti; } else { found = true; } } if (!found) { missing.add(ff); } } else { FontInformation ff = s.iterator().next(); if (!ff.isEmbedded) { missing.add(ff); } } } // } // for all pages // Iterator<FontInformation> it = ret.iterator(); // FontInformation prev = null; // LinkedList<FontInformation> toDelete = new // LinkedList<FontInformation>(); // while (it.hasNext()) { // FontInformation current = it.next(); // // if (prev!= null && prev.fontName.equals(current.fontName) && // (prev.fontType.startsWith("CIDFontType") || // current.fontType.startsWith("CIDFontType"))) // toDelete.add(current); // prev = current; // } // // //ret.removeAll(toDelete); // FontInformation[] retArray =toDelete.toArray(new FontInformation[0]); // if (missing.size() == 0) { missing = null; } else { System.out.println("Found missing fonts: " + f); System.out.println(missing); } return new PDFFontResults(new LinkedList<FontInformation>(ret), missing); }
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 w w w . j a va2 s . com*/ * @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 mergeXObj(COSDictionary sourcePageResources, FontInfo fontinfo, UniqueName uniqueName) throws IOException { COSDictionary xobj = (COSDictionary) sourcePageResources.getDictionaryObject(COSName.XOBJECT); if (xobj != null && pdfDoc.isMergeFontsEnabled()) { for (Map.Entry<COSName, COSBase> i : xobj.entrySet()) { COSObject v = (COSObject) i.getValue(); COSStream stream = (COSStream) v.getObject(); COSDictionary res = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); if (res != null) { COSDictionary src = (COSDictionary) res.getDictionaryObject(COSName.FONT); if (src != null) { COSDictionary target = (COSDictionary) sourcePageResources .getDictionaryObject(COSName.FONT); if (target == null) { sourcePageResources.setItem(COSName.FONT, src); } else { for (Map.Entry<COSName, COSBase> entry : src.entrySet()) { if (!target.keySet().contains(entry.getKey())) { target.setItem(uniqueName.getName(entry.getKey()), entry.getValue()); }// w w w.j a v a2s . c om } } PDFWriter writer = new MergeFontsPDFWriter(src, fontinfo, uniqueName, parentFonts, 0); String c = writer.writeText(new PDStream(stream)); if (c != null) { stream.removeItem(COSName.FILTER); newXObj.put(i.getKey(), c); for (Object e : src.keySet().toArray()) { COSName name = (COSName) e; src.setItem(uniqueName.getName(name), src.getItem(name)); src.removeItem(name); } } } } } } }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
private void transferDict(Map.Entry<COSName, COSBase> dict, UniqueName uniqueName) throws IOException { COSBase src;/*from w w w. ja v a2 s . c o m*/ if (dict.getValue() instanceof COSObject) { src = ((COSObject) dict.getValue()).getObject(); } else { src = dict.getValue(); } if (dict.getKey() != COSName.FONT && src instanceof COSDictionary) { String name = dict.getKey().getName(); PDFDictionary newDict = (PDFDictionary) targetPage.getPDFResources().get(name); if (newDict == null) { newDict = new PDFDictionary(targetPage.getPDFResources()); } COSDictionary srcDict = (COSDictionary) src; for (Map.Entry<COSName, COSBase> v : srcDict.entrySet()) { newDict.put(uniqueName.getName(v.getKey()), cloneForNewDocument(v.getValue())); } targetPage.getPDFResources().put(name, newDict); } }
From source file:org.apache.fop.render.pdf.PDFBoxAdapterTestCase.java
License:Apache License
private COSDictionary getFont(PDDocument doc, String internalname) throws IOException { PDPage page = (PDPage) doc.getDocumentCatalog().getPages().get(0); PDResources sourcePageResources = page.getResources(); COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT); return (COSDictionary) fonts.getDictionaryObject(internalname); }
From source file:se.streamsource.streamflow.web.application.pdf.Underlay.java
License:Apache License
private void mergePage(COSArray array, PDPage page) { int layoutPageNum = pageCount % layoutPages.size(); LayoutPage layoutPage = (LayoutPage) layoutPages.get(layoutPageNum); PDResources resources = page.findResources(); if (resources == null) { resources = new PDResources(); page.setResources(resources);/*from w ww. ja va 2 s . c om*/ } COSDictionary docResDict = resources.getCOSDictionary(); COSDictionary layoutResDict = layoutPage.res; mergeArray(COSName.PROC_SET, docResDict, layoutResDict); mergeDictionary(COSName.COLORSPACE, docResDict, layoutResDict, layoutPage.objectNameMap); mergeDictionary(COSName.FONT, docResDict, layoutResDict, layoutPage.objectNameMap); mergeDictionary(COSName.XOBJECT, docResDict, layoutResDict, layoutPage.objectNameMap); mergeDictionary(COSName.EXT_G_STATE, docResDict, layoutResDict, layoutPage.objectNameMap); array.add(0, layoutPage.contents); }