選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

PDFFactory.java 57KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.pdf;
  19. // Java
  20. import java.awt.geom.Point2D;
  21. import java.awt.geom.Rectangle2D;
  22. import java.io.ByteArrayInputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.text.DecimalFormat;
  26. import java.util.Arrays;
  27. import java.util.BitSet;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.SortedSet;
  32. import java.util.TreeSet;
  33. import org.apache.commons.io.IOUtils;
  34. import org.apache.commons.io.output.ByteArrayOutputStream;
  35. import org.apache.commons.logging.Log;
  36. import org.apache.commons.logging.LogFactory;
  37. import org.apache.xmlgraphics.java2d.color.NamedColorSpace;
  38. import org.apache.xmlgraphics.xmp.Metadata;
  39. import org.apache.fop.fonts.CIDFont;
  40. import org.apache.fop.fonts.CodePointMapping;
  41. import org.apache.fop.fonts.CustomFont;
  42. import org.apache.fop.fonts.EmbeddingMode;
  43. import org.apache.fop.fonts.FontDescriptor;
  44. import org.apache.fop.fonts.FontMetrics;
  45. import org.apache.fop.fonts.FontType;
  46. import org.apache.fop.fonts.LazyFont;
  47. import org.apache.fop.fonts.MultiByteFont;
  48. import org.apache.fop.fonts.SimpleSingleByteEncoding;
  49. import org.apache.fop.fonts.SingleByteEncoding;
  50. import org.apache.fop.fonts.SingleByteFont;
  51. import org.apache.fop.fonts.Typeface;
  52. import org.apache.fop.fonts.truetype.FontFileReader;
  53. import org.apache.fop.fonts.truetype.OFFontLoader;
  54. import org.apache.fop.fonts.truetype.OTFSubSetFile;
  55. import org.apache.fop.fonts.truetype.TTFSubSetFile;
  56. import org.apache.fop.fonts.type1.PFBData;
  57. import org.apache.fop.fonts.type1.PFBParser;
  58. import org.apache.fop.fonts.type1.Type1SubsetFile;
  59. /**
  60. * This class provides method to create and register PDF objects.
  61. */
  62. public class PDFFactory {
  63. /** Resolution of the User Space coordinate system (72dpi). */
  64. public static final int DEFAULT_PDF_RESOLUTION = 72;
  65. private PDFDocument document;
  66. private Log log = LogFactory.getLog(PDFFactory.class);
  67. private int subsetFontCounter = -1;
  68. /**
  69. * Creates a new PDFFactory.
  70. * @param document the parent PDFDocument needed to register the generated
  71. * objects
  72. */
  73. public PDFFactory(PDFDocument document) {
  74. this.document = document;
  75. }
  76. /**
  77. * Returns the parent PDFDocument associated with this factory.
  78. * @return PDFDocument the parent PDFDocument
  79. */
  80. public final PDFDocument getDocument() {
  81. return this.document;
  82. }
  83. /* ========================= structure objects ========================= */
  84. /**
  85. * Make a /Catalog (Root) object. This object is written in
  86. * the trailer.
  87. *
  88. * @param pages the pages pdf object that the root points to
  89. * @return the new pdf root object for this document
  90. */
  91. public PDFRoot makeRoot(PDFPages pages) {
  92. //Make a /Pages object. This object is written in the trailer.
  93. PDFRoot pdfRoot = new PDFRoot(document, pages);
  94. pdfRoot.setDocument(getDocument());
  95. getDocument().addTrailerObject(pdfRoot);
  96. return pdfRoot;
  97. }
  98. /**
  99. * Make a /Pages object. This object is written in the trailer.
  100. *
  101. * @return a new PDF Pages object for adding pages to
  102. */
  103. public PDFPages makePages() {
  104. PDFPages pdfPages = new PDFPages(getDocument());
  105. pdfPages.setDocument(getDocument());
  106. getDocument().addTrailerObject(pdfPages);
  107. return pdfPages;
  108. }
  109. /**
  110. * Make a /Resources object. This object is written in the trailer.
  111. *
  112. * @return a new PDF resources object
  113. */
  114. public PDFResources makeResources() {
  115. PDFResources pdfResources = new PDFResources(getDocument());
  116. pdfResources.setDocument(getDocument());
  117. getDocument().addTrailerObject(pdfResources);
  118. return pdfResources;
  119. }
  120. /**
  121. * make an /Info object
  122. *
  123. * @param prod string indicating application producing the PDF
  124. * @return the created /Info object
  125. */
  126. protected PDFInfo makeInfo(String prod) {
  127. /*
  128. * create a PDFInfo with the next object number and add to
  129. * list of objects
  130. */
  131. PDFInfo pdfInfo = new PDFInfo();
  132. // set the default producer
  133. pdfInfo.setProducer(prod);
  134. getDocument().registerObject(pdfInfo);
  135. return pdfInfo;
  136. }
  137. /**
  138. * Make a Metadata object.
  139. * @param meta the DOM Document containing the XMP metadata.
  140. * @param readOnly true if the metadata packet should be marked read-only
  141. * @return the newly created Metadata object
  142. */
  143. public PDFMetadata makeMetadata(Metadata meta, boolean readOnly) {
  144. PDFMetadata pdfMetadata = new PDFMetadata(meta, readOnly);
  145. getDocument().registerObject(pdfMetadata);
  146. return pdfMetadata;
  147. }
  148. /**
  149. * Make a OutputIntent dictionary.
  150. * @return the newly created OutputIntent dictionary
  151. */
  152. public PDFOutputIntent makeOutputIntent() {
  153. PDFOutputIntent outputIntent = new PDFOutputIntent();
  154. getDocument().registerObject(outputIntent);
  155. return outputIntent;
  156. }
  157. /**
  158. * Make a /Page object. The page is assigned an object number immediately
  159. * so references can already be made. The page must be added to the
  160. * PDFDocument later using addObject().
  161. *
  162. * @param resources resources object to use
  163. * @param pageIndex index of the page (zero-based)
  164. * @param mediaBox the MediaBox area
  165. * @param cropBox the CropBox area
  166. * @param bleedBox the BleedBox area
  167. * @param trimBox the TrimBox area
  168. *
  169. * @return the created /Page object
  170. */
  171. public PDFPage makePage(PDFResources resources, int pageIndex,
  172. Rectangle2D mediaBox, Rectangle2D cropBox,
  173. Rectangle2D bleedBox, Rectangle2D trimBox) {
  174. /*
  175. * create a PDFPage with the next object number, the given
  176. * resources, contents and dimensions
  177. */
  178. PDFPage page = new PDFPage(resources, pageIndex, mediaBox, cropBox, bleedBox, trimBox);
  179. getDocument().assignObjectNumber(page);
  180. getDocument().getPages().addPage(page);
  181. return page;
  182. }
  183. /**
  184. * Make a /Page object. The page is assigned an object number immediately
  185. * so references can already be made. The page must be added to the
  186. * PDFDocument later using addObject().
  187. *
  188. * @param resources resources object to use
  189. * @param pageWidth width of the page in points
  190. * @param pageHeight height of the page in points
  191. * @param pageIndex index of the page (zero-based)
  192. *
  193. * @return the created /Page object
  194. */
  195. public PDFPage makePage(PDFResources resources,
  196. int pageWidth, int pageHeight, int pageIndex) {
  197. Rectangle2D mediaBox = new Rectangle2D.Double(0, 0, pageWidth, pageHeight);
  198. return makePage(resources, pageIndex, mediaBox, mediaBox, mediaBox, mediaBox);
  199. }
  200. /**
  201. * Make a /Page object. The page is assigned an object number immediately
  202. * so references can already be made. The page must be added to the
  203. * PDFDocument later using addObject().
  204. *
  205. * @param resources resources object to use
  206. * @param pageWidth width of the page in points
  207. * @param pageHeight height of the page in points
  208. *
  209. * @return the created /Page object
  210. */
  211. public PDFPage makePage(PDFResources resources,
  212. int pageWidth, int pageHeight) {
  213. return makePage(resources, pageWidth, pageHeight, -1);
  214. }
  215. /* ========================= functions ================================= */
  216. /**
  217. * make a type Exponential interpolation function
  218. * (for shading usually)
  219. * @param domain List objects of Double objects.
  220. * This is the domain of the function.
  221. * See page 264 of the PDF 1.3 Spec.
  222. * @param range List of Doubles that is the Range of the function.
  223. * See page 264 of the PDF 1.3 Spec.
  224. * @param cZero This is a vector of Double objects which defines the function result
  225. * when x=0.
  226. *
  227. * This attribute is optional.
  228. * It's described on page 268 of the PDF 1.3 spec.
  229. * @param cOne This is a vector of Double objects which defines the function result
  230. * when x=1.
  231. *
  232. * This attribute is optional.
  233. * It's described on page 268 of the PDF 1.3 spec.
  234. * @param interpolationExponentN This is the inerpolation exponent.
  235. *
  236. * This attribute is required.
  237. * PDF Spec page 268
  238. *
  239. * @return the PDF function that was created
  240. */
  241. public PDFFunction makeFunction(List domain, List range, float[] cZero, float[] cOne,
  242. double interpolationExponentN) {
  243. PDFFunction function = new PDFFunction(domain, range, cZero, cOne, interpolationExponentN);
  244. function = registerFunction(function);
  245. return function;
  246. }
  247. /**
  248. * Registers a function against the document
  249. * @param function The function to register
  250. */
  251. public PDFFunction registerFunction(PDFFunction function) {
  252. PDFFunction oldfunc = getDocument().findFunction(function);
  253. if (oldfunc == null) {
  254. getDocument().registerObject(function);
  255. } else {
  256. function = oldfunc;
  257. }
  258. return function;
  259. }
  260. /* ========================= shadings ================================== */
  261. /**
  262. * Registers a shading object against the document
  263. * @param res The PDF resource context
  264. * @param shading The shading object to be registered
  265. */
  266. public PDFShading registerShading(PDFResourceContext res, PDFShading shading) {
  267. PDFShading oldshad = getDocument().findShading(shading);
  268. if (oldshad == null) {
  269. getDocument().registerObject(shading);
  270. } else {
  271. shading = oldshad;
  272. }
  273. // add this shading to resources
  274. if (res != null) {
  275. res.addShading(shading);
  276. }
  277. return shading;
  278. }
  279. /* ========================= patterns ================================== */
  280. /**
  281. * Make a tiling pattern
  282. *
  283. * @param res the PDF resource context to add the shading, may be null
  284. * @param thePatternType the type of pattern, which is 1 for tiling.
  285. * @param theResources the resources associated with this pattern
  286. * @param thePaintType 1 or 2, colored or uncolored.
  287. * @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
  288. * @param theBBox List of Doubles: The pattern cell bounding box
  289. * @param theXStep horizontal spacing
  290. * @param theYStep vertical spacing
  291. * @param theMatrix Optional List of Doubles transformation matrix
  292. * @param theXUID Optional vector of Integers that uniquely identify the pattern
  293. * @param thePatternDataStream The stream of pattern data to be tiled.
  294. * @return the PDF pattern that was created
  295. */
  296. public PDFPattern makePattern(PDFResourceContext res, int thePatternType,
  297. PDFResources theResources, int thePaintType, int theTilingType,
  298. List theBBox, double theXStep,
  299. double theYStep, List theMatrix,
  300. List theXUID, StringBuffer thePatternDataStream) {
  301. // PDFResources theResources
  302. PDFPattern pattern = new PDFPattern(theResources, 1,
  303. thePaintType, theTilingType,
  304. theBBox, theXStep, theYStep,
  305. theMatrix, theXUID,
  306. thePatternDataStream);
  307. PDFPattern oldpatt = getDocument().findPattern(pattern);
  308. if (oldpatt == null) {
  309. getDocument().registerObject(pattern);
  310. } else {
  311. pattern = oldpatt;
  312. }
  313. if (res != null) {
  314. res.addPattern(pattern);
  315. }
  316. return (pattern);
  317. }
  318. public PDFPattern registerPattern(PDFResourceContext res, PDFPattern pattern) {
  319. PDFPattern oldpatt = getDocument().findPattern(pattern);
  320. if (oldpatt == null) {
  321. getDocument().registerObject(pattern);
  322. } else {
  323. pattern = oldpatt;
  324. }
  325. if (res != null) {
  326. res.addPattern(pattern);
  327. }
  328. return pattern;
  329. }
  330. /* ============= named destinations and the name dictionary ============ */
  331. /**
  332. * Registers and returns newdest if it is unique. Otherwise, returns
  333. * the equal destination already present in the document.
  334. *
  335. * @param newdest a new, as yet unregistered destination
  336. * @return newdest if unique, else the already registered instance
  337. */
  338. protected PDFDestination getUniqueDestination(PDFDestination newdest) {
  339. PDFDestination existing = getDocument().findDestination(newdest);
  340. if (existing != null) {
  341. return existing;
  342. } else {
  343. getDocument().addDestination(newdest);
  344. return newdest;
  345. }
  346. }
  347. /**
  348. * Make a named destination.
  349. *
  350. * @param idRef ID Reference for this destination (the name of the destination)
  351. * @param goToRef Object reference to the GoTo Action
  352. * @return the newly created destrination
  353. */
  354. public PDFDestination makeDestination(String idRef, Object goToRef) {
  355. PDFDestination destination = new PDFDestination(idRef, goToRef);
  356. return getUniqueDestination(destination);
  357. }
  358. /**
  359. * Make a names dictionary (the /Names object).
  360. * @return the new PDFNames object
  361. */
  362. public PDFNames makeNames() {
  363. PDFNames names = new PDFNames();
  364. getDocument().assignObjectNumber(names);
  365. getDocument().addTrailerObject(names);
  366. return names;
  367. }
  368. /**
  369. * Make a names dictionary (the /PageLabels object).
  370. * @return the new PDFPageLabels object
  371. */
  372. public PDFPageLabels makePageLabels() {
  373. PDFPageLabels pageLabels = new PDFPageLabels();
  374. getDocument().assignObjectNumber(pageLabels);
  375. getDocument().addTrailerObject(pageLabels);
  376. return pageLabels;
  377. }
  378. /**
  379. * Make a the head object of the name dictionary (the /Dests object).
  380. *
  381. * @param destinationList a list of PDFDestination instances
  382. * @return the new PDFDests object
  383. */
  384. public PDFDests makeDests(List destinationList) {
  385. PDFDests dests;
  386. //TODO: Check why the below conditional branch is needed. Condition is always true...
  387. final boolean deep = true;
  388. //true for a "deep" structure (one node per entry), true for a "flat" structure
  389. if (deep) {
  390. dests = new PDFDests();
  391. PDFArray kids = new PDFArray(dests);
  392. Iterator iter = destinationList.iterator();
  393. while (iter.hasNext()) {
  394. PDFDestination dest = (PDFDestination)iter.next();
  395. PDFNameTreeNode node = new PDFNameTreeNode();
  396. getDocument().registerObject(node);
  397. node.setLowerLimit(dest.getIDRef());
  398. node.setUpperLimit(dest.getIDRef());
  399. node.setNames(new PDFArray(node));
  400. PDFArray names = node.getNames();
  401. names.add(dest);
  402. kids.add(node);
  403. }
  404. dests.setLowerLimit(((PDFNameTreeNode)kids.get(0)).getLowerLimit());
  405. dests.setUpperLimit(((PDFNameTreeNode)kids.get(kids.length() - 1)).getUpperLimit());
  406. dests.setKids(kids);
  407. } else {
  408. dests = new PDFDests(destinationList);
  409. }
  410. getDocument().registerObject(dests);
  411. return dests;
  412. }
  413. /**
  414. * Make a name tree node.
  415. *
  416. * @return the new name tree node
  417. */
  418. public PDFNameTreeNode makeNameTreeNode() {
  419. PDFNameTreeNode node = new PDFNameTreeNode();
  420. getDocument().registerObject(node);
  421. return node;
  422. }
  423. /* ========================= links ===================================== */
  424. // Some of the "yoffset-only" functions in this part are obsolete and can
  425. // possibly be removed or deprecated. Some are still called by PDFGraphics2D
  426. // (although that could be changed, they don't need the yOffset param anyway).
  427. /**
  428. * Create a PDF link to an existing PDFAction object
  429. *
  430. * @param rect the hotspot position in absolute coordinates
  431. * @param pdfAction the PDFAction that this link refers to
  432. * @return the new PDFLink object, or null if either rect or pdfAction is null
  433. */
  434. public PDFLink makeLink(Rectangle2D rect, PDFAction pdfAction) {
  435. if (rect == null || pdfAction == null) {
  436. return null;
  437. } else {
  438. PDFLink link = new PDFLink(rect);
  439. link.setAction(pdfAction);
  440. getDocument().registerObject(link);
  441. return link;
  442. // does findLink make sense? I mean, how often will it happen that several
  443. // links have the same target *and* the same hot rect? And findLink has to
  444. // walk and compare the entire link list everytime you call it...
  445. }
  446. }
  447. /**
  448. * Make an internal link.
  449. *
  450. * @param rect the hotspot position in absolute coordinates
  451. * @param page the target page reference value
  452. * @param dest the position destination
  453. * @return the new PDF link object
  454. */
  455. public PDFLink makeLink(Rectangle2D rect, String page, String dest) {
  456. PDFLink link = new PDFLink(rect);
  457. getDocument().registerObject(link);
  458. PDFGoTo gt = new PDFGoTo(page);
  459. gt.setDestination(dest);
  460. getDocument().registerObject(gt);
  461. PDFInternalLink internalLink = new PDFInternalLink(gt.referencePDF());
  462. link.setAction(internalLink);
  463. return link;
  464. }
  465. /**
  466. * Make a {@link PDFLink} object
  467. *
  468. * @param rect the clickable rectangle
  469. * @param destination the destination file
  470. * @param linkType the link type
  471. * @param yoffset the yoffset on the page for an internal link
  472. * @return the PDFLink object created
  473. */
  474. public PDFLink makeLink(Rectangle2D rect, String destination,
  475. int linkType, float yoffset) {
  476. //PDFLink linkObject;
  477. PDFLink link = new PDFLink(rect);
  478. if (linkType == PDFLink.EXTERNAL) {
  479. link.setAction(getExternalAction(destination, false));
  480. } else {
  481. // linkType is internal
  482. String goToReference = getGoToReference(destination, yoffset);
  483. PDFInternalLink internalLink = new PDFInternalLink(goToReference);
  484. link.setAction(internalLink);
  485. }
  486. PDFLink oldlink = getDocument().findLink(link);
  487. if (oldlink == null) {
  488. getDocument().registerObject(link);
  489. } else {
  490. link = oldlink;
  491. }
  492. return link;
  493. }
  494. private static final String EMBEDDED_FILE = "embedded-file:";
  495. /**
  496. * Create/find and return the appropriate external PDFAction according to the target
  497. *
  498. * @param target The external target. This may be a PDF file name
  499. * (optionally with internal page number or destination) or any type of URI.
  500. * @param newWindow boolean indicating whether the target should be
  501. * displayed in a new window
  502. * @return the PDFAction thus created or found
  503. */
  504. public PDFAction getExternalAction(String target, boolean newWindow) {
  505. int index;
  506. String targetLo = target.toLowerCase();
  507. if (target.startsWith(EMBEDDED_FILE)) {
  508. // File Attachments (Embedded Files)
  509. String filename = target.substring(EMBEDDED_FILE.length());
  510. return getActionForEmbeddedFile(filename, newWindow);
  511. } else if (targetLo.startsWith("http://")) {
  512. // HTTP URL?
  513. return new PDFUri(target);
  514. } else if (targetLo.startsWith("https://")) {
  515. // HTTPS URL?
  516. return new PDFUri(target);
  517. } else if (targetLo.startsWith("file://")) {
  518. // Non PDF files. Try to /Launch them.
  519. target = target.substring("file://".length());
  520. return getLaunchAction(target);
  521. } else if (targetLo.endsWith(".pdf")) {
  522. // Bare PDF file name?
  523. return getGoToPDFAction(target, null, -1, newWindow);
  524. } else if ((index = targetLo.indexOf(".pdf#page=")) > 0) {
  525. // PDF file + page?
  526. String filename = target.substring(0, index + 4);
  527. int page = Integer.parseInt(target.substring(index + 10));
  528. return getGoToPDFAction(filename, null, page, newWindow);
  529. } else if ((index = targetLo.indexOf(".pdf#dest=")) > 0) {
  530. // PDF file + destination?
  531. String filename = target.substring(0, index + 4);
  532. String dest = target.substring(index + 10);
  533. return getGoToPDFAction(filename, dest, -1, newWindow);
  534. } else {
  535. // None of the above? Default to URI:
  536. return new PDFUri(target);
  537. }
  538. }
  539. private PDFAction getActionForEmbeddedFile(String filename, boolean newWindow) {
  540. PDFNames names = getDocument().getRoot().getNames();
  541. if (names == null) {
  542. throw new IllegalStateException(
  543. "No Names dictionary present."
  544. + " Cannot create Launch Action for embedded file: " + filename);
  545. }
  546. PDFNameTreeNode embeddedFiles = names.getEmbeddedFiles();
  547. if (embeddedFiles == null) {
  548. throw new IllegalStateException(
  549. "No /EmbeddedFiles name tree present."
  550. + " Cannot create Launch Action for embedded file: " + filename);
  551. }
  552. //Find filespec reference for the embedded file
  553. filename = PDFText.toPDFString(filename, '_');
  554. PDFArray files = embeddedFiles.getNames();
  555. PDFReference embeddedFileRef = null;
  556. int i = 0;
  557. while (i < files.length()) {
  558. String name = (String)files.get(i);
  559. i++;
  560. PDFReference ref = (PDFReference)files.get(i);
  561. if (name.equals(filename)) {
  562. embeddedFileRef = ref;
  563. break;
  564. }
  565. i++;
  566. }
  567. if (embeddedFileRef == null) {
  568. throw new IllegalStateException(
  569. "No embedded file with name " + filename + " present.");
  570. }
  571. //Finally create the action
  572. //PDFLaunch action = new PDFLaunch(embeddedFileRef);
  573. //This works with Acrobat 8 but not with Acrobat 9
  574. //The following two options didn't seem to have any effect.
  575. //PDFGoToEmbedded action = new PDFGoToEmbedded(embeddedFileRef, 0, newWindow);
  576. //PDFGoToRemote action = new PDFGoToRemote(embeddedFileRef, 0, newWindow);
  577. //This finally seems to work:
  578. StringBuffer scriptBuffer = new StringBuffer();
  579. scriptBuffer.append("this.exportDataObject({cName:\"");
  580. scriptBuffer.append(filename);
  581. scriptBuffer.append("\", nLaunch:2});");
  582. PDFJavaScriptLaunchAction action = new PDFJavaScriptLaunchAction(scriptBuffer.toString());
  583. return action;
  584. }
  585. /**
  586. * Create or find a PDF GoTo with the given page reference string and Y offset,
  587. * and return its PDF object reference
  588. *
  589. * @param pdfPageRef the PDF page reference, e.g. "23 0 R"
  590. * @param yoffset the distance from the bottom of the page in points
  591. * @return the GoTo's object reference
  592. */
  593. public String getGoToReference(String pdfPageRef, float yoffset) {
  594. return getPDFGoTo(pdfPageRef, new Point2D.Float(0.0f, yoffset)).referencePDF();
  595. }
  596. /**
  597. * Finds and returns a PDFGoTo to the given page and position.
  598. * Creates the PDFGoTo if not found.
  599. *
  600. * @param pdfPageRef the PDF page reference
  601. * @param position the (X,Y) position in points
  602. *
  603. * @return the new or existing PDFGoTo object
  604. */
  605. public PDFGoTo getPDFGoTo(String pdfPageRef, Point2D position) {
  606. getDocument().getProfile().verifyActionAllowed();
  607. PDFGoTo gt = new PDFGoTo(pdfPageRef, position);
  608. PDFGoTo oldgt = getDocument().findGoTo(gt);
  609. if (oldgt == null) {
  610. getDocument().assignObjectNumber(gt);
  611. getDocument().addTrailerObject(gt);
  612. } else {
  613. gt = oldgt;
  614. }
  615. return gt;
  616. }
  617. /**
  618. * Create and return a goto pdf document action.
  619. * This creates a pdf files spec and pdf goto remote action.
  620. * It also checks available pdf objects so it will not create an
  621. * object if it already exists.
  622. *
  623. * @param file the pdf file name
  624. * @param dest the remote name destination, may be null
  625. * @param page the remote page number, -1 means not specified
  626. * @param newWindow boolean indicating whether the target should be
  627. * displayed in a new window
  628. * @return the pdf goto remote object
  629. */
  630. private PDFGoToRemote getGoToPDFAction(String file, String dest, int page, boolean newWindow) {
  631. getDocument().getProfile().verifyActionAllowed();
  632. PDFFileSpec fileSpec = new PDFFileSpec(file);
  633. PDFFileSpec oldspec = getDocument().findFileSpec(fileSpec);
  634. if (oldspec == null) {
  635. getDocument().registerObject(fileSpec);
  636. } else {
  637. fileSpec = oldspec;
  638. }
  639. PDFGoToRemote remote;
  640. if (dest == null && page == -1) {
  641. remote = new PDFGoToRemote(fileSpec, newWindow);
  642. } else if (dest != null) {
  643. remote = new PDFGoToRemote(fileSpec, dest, newWindow);
  644. } else {
  645. remote = new PDFGoToRemote(fileSpec, page, newWindow);
  646. }
  647. PDFGoToRemote oldremote = getDocument().findGoToRemote(remote);
  648. if (oldremote == null) {
  649. getDocument().registerObject(remote);
  650. } else {
  651. remote = oldremote;
  652. }
  653. return remote;
  654. }
  655. /**
  656. * Creates and returns a launch pdf document action using
  657. * <code>file</code> to create a file spcifiaciton for
  658. * the document/file to be opened with an external application.
  659. *
  660. * @param file the pdf file name
  661. * @return the pdf launch object
  662. */
  663. private PDFLaunch getLaunchAction(String file) {
  664. getDocument().getProfile().verifyActionAllowed();
  665. PDFFileSpec fileSpec = new PDFFileSpec(file);
  666. PDFFileSpec oldSpec = getDocument().findFileSpec(fileSpec);
  667. if (oldSpec == null) {
  668. getDocument().registerObject(fileSpec);
  669. } else {
  670. fileSpec = oldSpec;
  671. }
  672. PDFLaunch launch = new PDFLaunch(fileSpec);
  673. PDFLaunch oldLaunch = getDocument().findLaunch(launch);
  674. if (oldLaunch == null) {
  675. getDocument().registerObject(launch);
  676. } else {
  677. launch = oldLaunch;
  678. }
  679. return launch;
  680. }
  681. /**
  682. * Make an outline object and add it to the given parent
  683. *
  684. * @param parent the parent PDFOutline object (may be null)
  685. * @param label the title for the new outline object
  686. * @param actionRef the action reference string to be placed after the /A
  687. * @param showSubItems whether to initially display child outline items
  688. * @return the new PDF outline object
  689. */
  690. public PDFOutline makeOutline(PDFOutline parent, String label,
  691. PDFReference actionRef, boolean showSubItems) {
  692. PDFOutline pdfOutline = new PDFOutline(label, actionRef, showSubItems);
  693. if (parent != null) {
  694. parent.addOutline(pdfOutline);
  695. }
  696. getDocument().registerObject(pdfOutline);
  697. return pdfOutline;
  698. }
  699. /**
  700. * Make an outline object and add it to the given parent
  701. *
  702. * @param parent the parent PDFOutline object (may be null)
  703. * @param label the title for the new outline object
  704. * @param pdfAction the action that this outline item points to - must not be null!
  705. * @param showSubItems whether to initially display child outline items
  706. * @return the new PDFOutline object, or null if pdfAction is null
  707. */
  708. public PDFOutline makeOutline(PDFOutline parent, String label,
  709. PDFAction pdfAction, boolean showSubItems) {
  710. return pdfAction == null
  711. ? null
  712. : makeOutline(parent, label, new PDFReference(pdfAction.getAction()), showSubItems);
  713. }
  714. // This one is obsolete now, at least it isn't called from anywhere inside FOP
  715. /**
  716. * Make an outline object and add it to the given outline
  717. *
  718. * @param parent parent PDFOutline object which may be null
  719. * @param label the title for the new outline object
  720. * @param destination the reference string for the action to go to
  721. * @param yoffset the yoffset on the destination page
  722. * @param showSubItems whether to initially display child outline items
  723. * @return the new PDF outline object
  724. */
  725. public PDFOutline makeOutline(PDFOutline parent, String label,
  726. String destination, float yoffset,
  727. boolean showSubItems) {
  728. String goToRef = getGoToReference(destination, yoffset);
  729. return makeOutline(parent, label, new PDFReference(goToRef), showSubItems);
  730. }
  731. /* ========================= fonts ===================================== */
  732. /**
  733. * make a /Encoding object
  734. *
  735. * @param encodingName character encoding scheme name
  736. * @return the created /Encoding object
  737. */
  738. public PDFEncoding makeEncoding(String encodingName) {
  739. PDFEncoding encoding = new PDFEncoding(encodingName);
  740. getDocument().registerObject(encoding);
  741. return encoding;
  742. }
  743. /**
  744. * Make a Type1 /Font object.
  745. *
  746. * @param fontname internal name to use for this font (eg "F1")
  747. * @param basefont name of the base font (eg "Helvetica")
  748. * @param encoding character encoding scheme used by the font
  749. * @param metrics additional information about the font
  750. * @param descriptor additional information about the font
  751. * @return the created /Font object
  752. */
  753. public PDFFont makeFont(String fontname, String basefont,
  754. String encoding, FontMetrics metrics,
  755. FontDescriptor descriptor) {
  756. PDFFont preRegisteredfont = getDocument().findFont(fontname);
  757. if (preRegisteredfont != null) {
  758. return preRegisteredfont;
  759. }
  760. boolean forceToUnicode = true;
  761. if (descriptor == null) {
  762. //Usually Base 14 fonts
  763. PDFFont font = new PDFFont(fontname, FontType.TYPE1, basefont, encoding);
  764. getDocument().registerObject(font);
  765. if (forceToUnicode && !PDFEncoding.isPredefinedEncoding(encoding)) {
  766. SingleByteEncoding mapping;
  767. if (encoding != null) {
  768. mapping = CodePointMapping.getMapping(encoding);
  769. } else {
  770. //for Symbol and ZapfDingbats where encoding must be null in PDF
  771. Typeface tf = (Typeface)metrics;
  772. mapping = CodePointMapping.getMapping(tf.getEncodingName());
  773. }
  774. generateToUnicodeCmap(font, mapping);
  775. }
  776. return font;
  777. } else {
  778. FontType fonttype = metrics.getFontType();
  779. String fontPrefix = descriptor.isSubsetEmbedded() ? createSubsetFontPrefix() : "";
  780. String subsetFontName = fontPrefix + basefont;
  781. PDFFontDescriptor pdfdesc = makeFontDescriptor(descriptor, fontPrefix);
  782. PDFFont font = null;
  783. font = PDFFont.createFont(fontname, fonttype, subsetFontName, null);
  784. if (descriptor instanceof RefPDFFont) {
  785. font.setObjectNumber(((RefPDFFont)descriptor).getRef().getObjectNumber());
  786. font.setDocument(getDocument());
  787. getDocument().addObject(font);
  788. } else {
  789. getDocument().registerObject(font);
  790. }
  791. if ((fonttype == FontType.TYPE0 || fonttype == FontType.CIDTYPE0)) {
  792. font.setEncoding(encoding);
  793. CIDFont cidMetrics;
  794. if (metrics instanceof LazyFont) {
  795. cidMetrics = (CIDFont)((LazyFont) metrics).getRealFont();
  796. } else {
  797. cidMetrics = (CIDFont)metrics;
  798. }
  799. PDFCIDSystemInfo sysInfo = new PDFCIDSystemInfo(cidMetrics.getRegistry(),
  800. cidMetrics.getOrdering(), cidMetrics.getSupplement());
  801. sysInfo.setDocument(document);
  802. assert pdfdesc instanceof PDFCIDFontDescriptor;
  803. PDFCIDFont cidFont = new PDFCIDFont(subsetFontName, cidMetrics.getCIDType(),
  804. cidMetrics.getDefaultWidth(), getFontWidths(cidMetrics), sysInfo,
  805. (PDFCIDFontDescriptor) pdfdesc);
  806. getDocument().registerObject(cidFont);
  807. PDFCMap cmap;
  808. if (cidMetrics instanceof MultiByteFont && ((MultiByteFont) cidMetrics).getCmapStream() != null) {
  809. cmap = new PDFCMap("fop-ucs-H", null);
  810. try {
  811. cmap.setData(IOUtils.toByteArray(((MultiByteFont) cidMetrics).getCmapStream()));
  812. } catch (IOException e) {
  813. throw new RuntimeException(e);
  814. }
  815. } else {
  816. cmap = new PDFToUnicodeCMap(cidMetrics.getCIDSet().getChars(), "fop-ucs-H",
  817. new PDFCIDSystemInfo("Adobe", "Identity", 0), false);
  818. }
  819. getDocument().registerObject(cmap);
  820. assert font instanceof PDFFontType0;
  821. ((PDFFontType0)font).setCMAP(cmap);
  822. ((PDFFontType0)font).setDescendantFonts(cidFont);
  823. } else {
  824. assert font instanceof PDFFontNonBase14;
  825. PDFFontNonBase14 nonBase14 = (PDFFontNonBase14)font;
  826. nonBase14.setDescriptor(pdfdesc);
  827. SingleByteFont singleByteFont;
  828. if (metrics instanceof LazyFont) {
  829. singleByteFont = (SingleByteFont)((LazyFont)metrics).getRealFont();
  830. } else {
  831. singleByteFont = (SingleByteFont)metrics;
  832. }
  833. int firstChar = 0;
  834. int lastChar = 0;
  835. boolean defaultChars = false;
  836. if (singleByteFont.getEmbeddingMode() == EmbeddingMode.SUBSET) {
  837. Map<Integer, Integer> usedGlyphs = singleByteFont.getUsedGlyphs();
  838. if (fonttype == FontType.TYPE1 && usedGlyphs.size() > 0) {
  839. SortedSet<Integer> keys = new TreeSet<Integer>(usedGlyphs.keySet());
  840. keys.remove(0);
  841. if (keys.size() > 0) {
  842. firstChar = keys.first();
  843. lastChar = keys.last();
  844. int[] newWidths = new int[(lastChar - firstChar) + 1];
  845. for (int i = firstChar; i < lastChar + 1; i++) {
  846. if (usedGlyphs.get(i) != null) {
  847. if (i - singleByteFont.getFirstChar() < metrics.getWidths().length) {
  848. newWidths[i - firstChar] = metrics.getWidths()[i
  849. - singleByteFont.getFirstChar()];
  850. } else {
  851. defaultChars = true;
  852. break;
  853. }
  854. } else {
  855. newWidths[i - firstChar] = 0;
  856. }
  857. }
  858. nonBase14.setWidthMetrics(firstChar,
  859. lastChar,
  860. new PDFArray(null, newWidths));
  861. }
  862. } else {
  863. defaultChars = true;
  864. }
  865. } else {
  866. defaultChars = true;
  867. }
  868. if (defaultChars) {
  869. firstChar = singleByteFont.getFirstChar();
  870. lastChar = singleByteFont.getLastChar();
  871. nonBase14.setWidthMetrics(firstChar,
  872. lastChar,
  873. new PDFArray(null, metrics.getWidths()));
  874. }
  875. //Handle encoding
  876. SingleByteEncoding mapping = singleByteFont.getEncoding();
  877. if (singleByteFont.isSymbolicFont()) {
  878. //no encoding, use the font's encoding
  879. if (forceToUnicode) {
  880. generateToUnicodeCmap(nonBase14, mapping);
  881. }
  882. } else if (PDFEncoding.isPredefinedEncoding(mapping.getName())) {
  883. font.setEncoding(mapping.getName());
  884. //No ToUnicode CMap necessary if PDF 1.4, chapter 5.9 (page 368) is to be
  885. //believed.
  886. } else if (mapping.getName().equals("FOPPDFEncoding")) {
  887. String[] charNameMap = mapping.getCharNameMap();
  888. char[] intmap = mapping.getUnicodeCharMap();
  889. PDFArray differences = new PDFArray();
  890. int len = intmap.length;
  891. if (charNameMap.length < len) {
  892. len = charNameMap.length;
  893. }
  894. int last = 0;
  895. for (int i = 0; i < len; i++) {
  896. if (intmap[i] - 1 != last) {
  897. differences.add(intmap[i]);
  898. }
  899. last = intmap[i];
  900. differences.add(new PDFName(charNameMap[i]));
  901. }
  902. PDFEncoding pdfEncoding = new PDFEncoding(singleByteFont.getEncodingName());
  903. getDocument().registerObject(pdfEncoding);
  904. pdfEncoding.setDifferences(differences);
  905. font.setEncoding(pdfEncoding);
  906. if (mapping.getUnicodeCharMap() != null) {
  907. generateToUnicodeCmap(nonBase14, mapping);
  908. }
  909. } else {
  910. Object pdfEncoding = createPDFEncoding(mapping,
  911. singleByteFont.getFontName());
  912. if (pdfEncoding instanceof PDFEncoding) {
  913. font.setEncoding((PDFEncoding)pdfEncoding);
  914. } else {
  915. font.setEncoding((String)pdfEncoding);
  916. }
  917. if (forceToUnicode) {
  918. generateToUnicodeCmap(nonBase14, mapping);
  919. }
  920. }
  921. //Handle additional encodings (characters outside the primary encoding)
  922. if (singleByteFont.hasAdditionalEncodings()) {
  923. for (int i = 0, c = singleByteFont.getAdditionalEncodingCount(); i < c; i++) {
  924. SimpleSingleByteEncoding addEncoding
  925. = singleByteFont.getAdditionalEncoding(i);
  926. String name = fontname + "_" + (i + 1);
  927. Object pdfenc = createPDFEncoding(addEncoding,
  928. singleByteFont.getFontName());
  929. PDFFontNonBase14 addFont = (PDFFontNonBase14)PDFFont.createFont(
  930. name, fonttype,
  931. basefont, pdfenc);
  932. addFont.setDescriptor(pdfdesc);
  933. addFont.setWidthMetrics(
  934. addEncoding.getFirstChar(),
  935. addEncoding.getLastChar(),
  936. new PDFArray(null, singleByteFont.getAdditionalWidths(i)));
  937. getDocument().registerObject(addFont);
  938. getDocument().getResources().addFont(addFont);
  939. if (forceToUnicode) {
  940. generateToUnicodeCmap(addFont, addEncoding);
  941. }
  942. }
  943. }
  944. }
  945. return font;
  946. }
  947. }
  948. private void generateToUnicodeCmap(PDFFont font, SingleByteEncoding encoding) {
  949. PDFCMap cmap = new PDFToUnicodeCMap(encoding.getUnicodeCharMap(),
  950. "fop-ucs-H",
  951. new PDFCIDSystemInfo("Adobe", "Identity", 0), true);
  952. getDocument().registerObject(cmap);
  953. font.setToUnicode(cmap);
  954. }
  955. /**
  956. * Creates a PDFEncoding instance from a CodePointMapping instance.
  957. * @param encoding the code point mapping (encoding)
  958. * @param fontName ...
  959. * @return the PDF Encoding dictionary (or a String with the predefined encoding)
  960. */
  961. public Object createPDFEncoding(SingleByteEncoding encoding, String fontName) {
  962. return PDFEncoding.createPDFEncoding(encoding, fontName);
  963. }
  964. private PDFWArray getFontWidths(CIDFont cidFont) {
  965. // Create widths for reencoded chars
  966. PDFWArray warray = new PDFWArray();
  967. if (cidFont instanceof MultiByteFont && ((MultiByteFont)cidFont).getWidthsMap() != null) {
  968. Map<Integer, Integer> map = ((MultiByteFont)cidFont).getWidthsMap();
  969. for (Map.Entry<Integer, Integer> cid : map.entrySet()) {
  970. warray.addEntry(cid.getKey(), new int[] {cid.getValue()});
  971. }
  972. // List<Integer> l = new ArrayList<Integer>(map.keySet());
  973. // for (int i=0; i<map.size(); i++) {
  974. // int cid = l.get(i);
  975. // List<Integer> cids = new ArrayList<Integer>();
  976. // cids.add(map.get(cid));
  977. // while (i<map.size()-1 && l.get(i) + 1 == l.get(i + 1)) {
  978. // cids.add(map.get(l.get(i + 1)));
  979. // i++;
  980. // }
  981. // int[] cidsints = new int[cids.size()];
  982. // for (int j=0; j<cids.size(); j++) {
  983. // cidsints[j] = cids.get(j);
  984. // }
  985. // warray.addEntry(cid, cidsints);
  986. // }
  987. } else {
  988. int[] widths = cidFont.getCIDSet().getWidths();
  989. warray.addEntry(0, widths);
  990. }
  991. return warray;
  992. }
  993. private String createSubsetFontPrefix() {
  994. subsetFontCounter++;
  995. DecimalFormat counterFormat = new DecimalFormat("00000");
  996. String counterString = counterFormat.format(subsetFontCounter);
  997. // Subset prefix as described in chapter 5.5.3 of PDF 1.4
  998. StringBuffer sb = new StringBuffer("E");
  999. for (char c : counterString.toCharArray()) {
  1000. // translate numbers to uppercase characters
  1001. sb.append((char) (c + ('A' - '0')));
  1002. }
  1003. sb.append("+");
  1004. return sb.toString();
  1005. }
  1006. /**
  1007. * make a /FontDescriptor object
  1008. *
  1009. * @param desc the font descriptor
  1010. * @param fontPrefix the String with which to prefix the font name
  1011. * @return the new PDF font descriptor
  1012. */
  1013. private PDFFontDescriptor makeFontDescriptor(FontDescriptor desc, String fontPrefix) {
  1014. PDFFontDescriptor descriptor = null;
  1015. if (desc.getFontType() == FontType.TYPE0 || desc.getFontType() == FontType.CIDTYPE0) {
  1016. // CID Font
  1017. descriptor = new PDFCIDFontDescriptor(fontPrefix + desc.getEmbedFontName(),
  1018. desc.getFontBBox(),
  1019. desc.getCapHeight(),
  1020. desc.getFlags(),
  1021. desc.getItalicAngle(),
  1022. desc.getStemV(), null);
  1023. } else {
  1024. // Create normal FontDescriptor
  1025. descriptor = new PDFFontDescriptor(fontPrefix + desc.getEmbedFontName(),
  1026. desc.getAscender(),
  1027. desc.getDescender(),
  1028. desc.getCapHeight(),
  1029. desc.getFlags(),
  1030. new PDFRectangle(desc.getFontBBox()),
  1031. desc.getItalicAngle(),
  1032. desc.getStemV());
  1033. }
  1034. getDocument().registerObject(descriptor);
  1035. // Check if the font is embeddable
  1036. if (desc.isEmbeddable()) {
  1037. AbstractPDFStream stream = makeFontFile(desc, fontPrefix);
  1038. if (stream != null) {
  1039. descriptor.setFontFile(desc.getFontType(), stream);
  1040. getDocument().registerObject(stream);
  1041. }
  1042. CustomFont font = getCustomFont(desc);
  1043. if (font instanceof CIDFont) {
  1044. CIDFont cidFont = (CIDFont)font;
  1045. buildCIDSet(descriptor, cidFont);
  1046. }
  1047. }
  1048. return descriptor;
  1049. }
  1050. private void buildCIDSet(PDFFontDescriptor descriptor, CIDFont cidFont) {
  1051. BitSet cidSet = cidFont.getCIDSet().getGlyphIndices();
  1052. PDFStream pdfStream = makeStream(null, true);
  1053. ByteArrayOutputStream baout = new ByteArrayOutputStream(cidSet.length() / 8 + 1);
  1054. int value = 0;
  1055. for (int i = 0, c = cidSet.length(); i < c; i++) {
  1056. int shift = i % 8;
  1057. boolean b = cidSet.get(i);
  1058. if (b) {
  1059. value |= 1 << 7 - shift;
  1060. }
  1061. if (shift == 7) {
  1062. baout.write(value);
  1063. value = 0;
  1064. }
  1065. }
  1066. baout.write(value);
  1067. try {
  1068. pdfStream.setData(baout.toByteArray());
  1069. descriptor.setCIDSet(pdfStream);
  1070. } catch (IOException ioe) {
  1071. log.error(
  1072. "Failed to write CIDSet [" + cidFont + "] "
  1073. + cidFont.getEmbedFontName(), ioe);
  1074. } finally {
  1075. IOUtils.closeQuietly(baout);
  1076. }
  1077. }
  1078. /**
  1079. * Embeds a font.
  1080. * @param desc FontDescriptor of the font.
  1081. * @return PDFStream The embedded font file
  1082. */
  1083. public AbstractPDFStream makeFontFile(FontDescriptor desc, String fontPrefix) {
  1084. if (desc.getFontType() == FontType.OTHER) {
  1085. throw new IllegalArgumentException("Trying to embed unsupported font type: "
  1086. + desc.getFontType());
  1087. }
  1088. CustomFont font = getCustomFont(desc);
  1089. InputStream in = null;
  1090. try {
  1091. in = font.getInputStream();
  1092. if (in == null) {
  1093. return null;
  1094. }
  1095. AbstractPDFStream embeddedFont = null;
  1096. if (desc.getFontType() == FontType.TYPE0) {
  1097. MultiByteFont mbfont = (MultiByteFont) font;
  1098. FontFileReader reader = new FontFileReader(in);
  1099. byte[] fontBytes;
  1100. String header = OFFontLoader.readHeader(reader);
  1101. boolean isCFF = mbfont.isOTFFile();
  1102. if (font.getEmbeddingMode() == EmbeddingMode.FULL) {
  1103. fontBytes = reader.getAllBytes();
  1104. if (isCFF) {
  1105. //Ensure version 1.6 for full OTF CFF embedding
  1106. document.setPDFVersion(Version.V1_6);
  1107. }
  1108. } else {
  1109. fontBytes = getFontSubsetBytes(reader, mbfont, header, fontPrefix, desc,
  1110. isCFF);
  1111. }
  1112. embeddedFont = getFontStream(font, fontBytes, isCFF);
  1113. } else if (desc.getFontType() == FontType.TYPE1) {
  1114. if (font.getEmbeddingMode() != EmbeddingMode.SUBSET) {
  1115. embeddedFont = fullyEmbedType1Font(in);
  1116. } else {
  1117. assert font instanceof SingleByteFont;
  1118. SingleByteFont sbfont = (SingleByteFont)font;
  1119. Type1SubsetFile pfbFile = new Type1SubsetFile();
  1120. byte[] subsetData = pfbFile.createSubset(in, sbfont);
  1121. InputStream subsetStream = new ByteArrayInputStream(subsetData);
  1122. PFBParser parser = new PFBParser();
  1123. PFBData pfb = parser.parsePFB(subsetStream);
  1124. embeddedFont = new PDFT1Stream();
  1125. ((PDFT1Stream) embeddedFont).setData(pfb);
  1126. }
  1127. } else if (desc.getFontType() == FontType.TYPE1C) {
  1128. byte[] file = IOUtils.toByteArray(in);
  1129. PDFCFFStream embeddedFont2 = new PDFCFFStream("Type1C");
  1130. embeddedFont2.setData(file);
  1131. return embeddedFont2;
  1132. } else if (desc.getFontType() == FontType.CIDTYPE0) {
  1133. byte[] file = IOUtils.toByteArray(in);
  1134. PDFCFFStream embeddedFont2 = new PDFCFFStream("CIDFontType0C");
  1135. embeddedFont2.setData(file);
  1136. return embeddedFont2;
  1137. } else {
  1138. byte[] file = IOUtils.toByteArray(in);
  1139. embeddedFont = new PDFTTFStream(file.length);
  1140. ((PDFTTFStream) embeddedFont).setData(file, file.length);
  1141. }
  1142. /*
  1143. embeddedFont.getFilterList().addFilter("flate");
  1144. if (getDocument().isEncryptionActive()) {
  1145. getDocument().applyEncryption(embeddedFont);
  1146. } else {
  1147. embeddedFont.getFilterList().addFilter("ascii-85");
  1148. }*/
  1149. return embeddedFont;
  1150. } catch (IOException ioe) {
  1151. log.error("Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe);
  1152. return null;
  1153. } finally {
  1154. IOUtils.closeQuietly(in);
  1155. }
  1156. }
  1157. private AbstractPDFStream fullyEmbedType1Font(InputStream in) throws IOException {
  1158. PFBParser parser = new PFBParser();
  1159. PFBData pfb = parser.parsePFB(in);
  1160. AbstractPDFStream embeddedFont = new PDFT1Stream();
  1161. ((PDFT1Stream) embeddedFont).setData(pfb);
  1162. return embeddedFont;
  1163. }
  1164. private byte[] getFontSubsetBytes(FontFileReader reader, MultiByteFont mbfont, String header,
  1165. String fontPrefix, FontDescriptor desc, boolean isCFF) throws IOException {
  1166. if (isCFF) {
  1167. OTFSubSetFile otfFile = new OTFSubSetFile();
  1168. otfFile.readFont(reader, fontPrefix + desc.getEmbedFontName(), header, mbfont);
  1169. return otfFile.getFontSubset();
  1170. } else {
  1171. TTFSubSetFile otfFile = new TTFSubSetFile();
  1172. otfFile.readFont(reader, mbfont.getTTCName(), header, mbfont.getUsedGlyphs());
  1173. return otfFile.getFontSubset();
  1174. }
  1175. }
  1176. private AbstractPDFStream getFontStream(CustomFont font, byte[] fontBytes, boolean isCFF)
  1177. throws IOException {
  1178. AbstractPDFStream embeddedFont;
  1179. if (isCFF) {
  1180. embeddedFont = new PDFCFFStreamType0C(font.getEmbeddingMode() == EmbeddingMode.FULL);
  1181. ((PDFCFFStreamType0C) embeddedFont).setData(fontBytes, fontBytes.length);
  1182. } else {
  1183. embeddedFont = new PDFTTFStream(fontBytes.length);
  1184. ((PDFTTFStream) embeddedFont).setData(fontBytes, fontBytes.length);
  1185. }
  1186. return embeddedFont;
  1187. }
  1188. private CustomFont getCustomFont(FontDescriptor desc) {
  1189. Typeface tempFont;
  1190. if (desc instanceof LazyFont) {
  1191. tempFont = ((LazyFont)desc).getRealFont();
  1192. } else {
  1193. tempFont = (Typeface)desc;
  1194. }
  1195. if (!(tempFont instanceof CustomFont)) {
  1196. throw new IllegalArgumentException(
  1197. "FontDescriptor must be instance of CustomFont, but is a "
  1198. + desc.getClass().getName());
  1199. }
  1200. return (CustomFont)tempFont;
  1201. }
  1202. /* ========================= streams =================================== */
  1203. /**
  1204. * Make a stream object
  1205. *
  1206. * @param type the type of stream to be created
  1207. * @param add if true then the stream will be added immediately
  1208. * @return the stream object created
  1209. */
  1210. public PDFStream makeStream(String type, boolean add) {
  1211. // create a PDFStream with the next object number
  1212. // and add it to the list of objects
  1213. PDFStream obj = new PDFStream();
  1214. obj.setDocument(getDocument());
  1215. obj.getFilterList().addDefaultFilters(
  1216. getDocument().getFilterMap(),
  1217. type);
  1218. if (add) {
  1219. getDocument().registerObject(obj);
  1220. }
  1221. //getDocument().applyEncryption(obj);
  1222. return obj;
  1223. }
  1224. /**
  1225. * Create a PDFICCStream
  1226. * @see PDFImageXObject
  1227. * @see org.apache.fop.pdf.PDFDeviceColorSpace
  1228. * @return the new PDF ICC stream object
  1229. */
  1230. public PDFICCStream makePDFICCStream() {
  1231. PDFICCStream iccStream = new PDFICCStream();
  1232. getDocument().registerObject(iccStream);
  1233. //getDocument().applyEncryption(iccStream);
  1234. return iccStream;
  1235. }
  1236. /* ========================= misc. objects ============================= */
  1237. /**
  1238. * Makes a new ICCBased color space and registers it in the resource context.
  1239. * @param res the PDF resource context to add the shading, may be null
  1240. * @param explicitName the explicit name for the color space, may be null
  1241. * @param iccStream the ICC stream to associate with this color space
  1242. * @return the newly instantiated color space
  1243. */
  1244. public PDFICCBasedColorSpace makeICCBasedColorSpace(PDFResourceContext res,
  1245. String explicitName, PDFICCStream iccStream) {
  1246. PDFICCBasedColorSpace cs = new PDFICCBasedColorSpace(explicitName, iccStream);
  1247. getDocument().registerObject(cs);
  1248. if (res != null) {
  1249. res.getPDFResources().addColorSpace(cs);
  1250. } else {
  1251. getDocument().getResources().addColorSpace(cs);
  1252. }
  1253. return cs;
  1254. }
  1255. /**
  1256. * Create a new Separation color space.
  1257. * @param res the resource context (may be null)
  1258. * @param ncs the named color space to map to a separation color space
  1259. * @return the newly created Separation color space
  1260. */
  1261. public PDFSeparationColorSpace makeSeparationColorSpace(PDFResourceContext res,
  1262. NamedColorSpace ncs) {
  1263. String colorName = ncs.getColorName();
  1264. final Double zero = new Double(0d);
  1265. final Double one = new Double(1d);
  1266. List domain = Arrays.asList(new Double[] {zero, one});
  1267. List range = Arrays.asList(new Double[] {zero, one, zero, one, zero, one});
  1268. float[] cZero = new float[] {1f, 1f, 1f};
  1269. float[] cOne = ncs.getRGBColor().getColorComponents(null);
  1270. PDFFunction tintFunction = makeFunction(domain, range, cZero, cOne, 1.0d);
  1271. PDFSeparationColorSpace cs = new PDFSeparationColorSpace(colorName, tintFunction);
  1272. getDocument().registerObject(cs);
  1273. if (res != null) {
  1274. res.getPDFResources().addColorSpace(cs);
  1275. } else {
  1276. getDocument().getResources().addColorSpace(cs);
  1277. }
  1278. return cs;
  1279. }
  1280. /**
  1281. * Make an Array object (ex. Widths array for a font).
  1282. *
  1283. * @param values the int array values
  1284. * @return the PDF Array with the int values
  1285. */
  1286. public PDFArray makeArray(int[] values) {
  1287. PDFArray array = new PDFArray(null, values);
  1288. getDocument().registerObject(array);
  1289. return array;
  1290. }
  1291. /**
  1292. * make an ExtGState for extra graphics options
  1293. * This tries to find a GState that will setup the correct values
  1294. * for the current context. If there is no suitable GState it will
  1295. * create a new one.
  1296. *
  1297. * @param settings the settings required by the caller
  1298. * @param current the current GState of the current PDF context
  1299. * @return a PDF GState, either an existing GState or a new one
  1300. */
  1301. public PDFGState makeGState(Map settings, PDFGState current) {
  1302. // try to locate a gstate that has all the settings
  1303. // or will inherit from the current gstate
  1304. // compare "DEFAULT + settings" with "current + each gstate"
  1305. PDFGState wanted = new PDFGState();
  1306. wanted.addValues(PDFGState.DEFAULT);
  1307. wanted.addValues(settings);
  1308. PDFGState existing = getDocument().findGState(wanted, current);
  1309. if (existing != null) {
  1310. return existing;
  1311. }
  1312. PDFGState gstate = new PDFGState();
  1313. gstate.addValues(settings);
  1314. getDocument().registerObject(gstate);
  1315. return gstate;
  1316. }
  1317. /**
  1318. * Make an annotation list object
  1319. *
  1320. * @return the annotation list object created
  1321. */
  1322. public PDFAnnotList makeAnnotList() {
  1323. PDFAnnotList obj = new PDFAnnotList();
  1324. getDocument().assignObjectNumber(obj);
  1325. return obj;
  1326. }
  1327. public PDFLayer makeLayer(String id) {
  1328. PDFLayer layer = new PDFLayer(id);
  1329. getDocument().registerObject(layer);
  1330. return layer;
  1331. }
  1332. public PDFSetOCGStateAction makeSetOCGStateAction(String id) {
  1333. PDFSetOCGStateAction action = new PDFSetOCGStateAction(id);
  1334. getDocument().registerObject(action);
  1335. return action;
  1336. }
  1337. public PDFTransitionAction makeTransitionAction(String id) {
  1338. PDFTransitionAction action = new PDFTransitionAction(id);
  1339. getDocument().registerObject(action);
  1340. return action;
  1341. }
  1342. public PDFNavigator makeNavigator(String id) {
  1343. PDFNavigator navigator = new PDFNavigator(id);
  1344. getDocument().registerObject(navigator);
  1345. return navigator;
  1346. }
  1347. }