You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PDFFactory.java 66KB

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