/* * Copyright (C) 2008-2009, Google Inc. * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.patch; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; public class PatchTest extends TestCase { public void testEmpty() { final Patch p = new Patch(); assertTrue(p.getFiles().isEmpty()); assertTrue(p.getErrors().isEmpty()); } public void testParse_ConfigCaseInsensitive() throws IOException { final Patch p = parseTestPatchFile(); assertEquals(2, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); final FileHeader fRepositoryConfigTest = p.getFiles().get(0); final FileHeader fRepositoryConfig = p.getFiles().get(1); assertEquals( "org.eclipse.jgit.test/tst/org/spearce/jgit/lib/RepositoryConfigTest.java", fRepositoryConfigTest.getNewName()); assertEquals( "org.eclipse.jgit/src/org/spearce/jgit/lib/RepositoryConfig.java", fRepositoryConfig.getNewName()); assertEquals(572, fRepositoryConfigTest.startOffset); assertEquals(1490, fRepositoryConfig.startOffset); assertEquals("da7e704", fRepositoryConfigTest.getOldId().name()); assertEquals("34ce04a", fRepositoryConfigTest.getNewId().name()); assertSame(FileHeader.PatchType.UNIFIED, fRepositoryConfigTest .getPatchType()); assertSame(FileMode.REGULAR_FILE, fRepositoryConfigTest.getOldMode()); assertSame(FileMode.REGULAR_FILE, fRepositoryConfigTest.getNewMode()); assertEquals(1, fRepositoryConfigTest.getHunks().size()); { final HunkHeader h = fRepositoryConfigTest.getHunks().get(0); assertSame(fRepositoryConfigTest, h.getFileHeader()); assertEquals(921, h.startOffset); assertEquals(109, h.getOldImage().getStartLine()); assertEquals(4, h.getOldImage().getLineCount()); assertEquals(109, h.getNewStartLine()); assertEquals(11, h.getNewLineCount()); assertEquals(4, h.getLinesContext()); assertEquals(7, h.getOldImage().getLinesAdded()); assertEquals(0, h.getOldImage().getLinesDeleted()); assertSame(fRepositoryConfigTest.getOldId(), h.getOldImage() .getId()); assertEquals(1490, h.endOffset); } assertEquals("45c2f8a", fRepositoryConfig.getOldId().name()); assertEquals("3291bba", fRepositoryConfig.getNewId().name()); assertSame(FileHeader.PatchType.UNIFIED, fRepositoryConfig .getPatchType()); assertSame(FileMode.REGULAR_FILE, fRepositoryConfig.getOldMode()); assertSame(FileMode.REGULAR_FILE, fRepositoryConfig.getNewMode()); assertEquals(3, fRepositoryConfig.getHunks().size()); { final HunkHeader h = fRepositoryConfig.getHunks().get(0); assertSame(fRepositoryConfig, h.getFileHeader()); assertEquals(1803, h.startOffset); assertEquals(236, h.getOldImage().getStartLine()); assertEquals(9, h.getOldImage().getLineCount()); assertEquals(236, h.getNewStartLine()); assertEquals(9, h.getNewLineCount()); assertEquals(7, h.getLinesContext()); assertEquals(2, h.getOldImage().getLinesAdded()); assertEquals(2, h.getOldImage().getLinesDeleted()); assertSame(fRepositoryConfig.getOldId(), h.getOldImage().getId()); assertEquals(2434, h.endOffset); } { final HunkHeader h = fRepositoryConfig.getHunks().get(1); assertEquals(2434, h.startOffset); assertEquals(300, h.getOldImage().getStartLine()); assertEquals(7, h.getOldImage().getLineCount()); assertEquals(300, h.getNewStartLine()); assertEquals(7, h.getNewLineCount()); assertEquals(6, h.getLinesContext()); assertEquals(1, h.getOldImage().getLinesAdded()); assertEquals(1, h.getOldImage().getLinesDeleted()); assertEquals(2816, h.endOffset); } { final HunkHeader h = fRepositoryConfig.getHunks().get(2); assertEquals(2816, h.startOffset); assertEquals(954, h.getOldImage().getStartLine()); assertEquals(7, h.getOldImage().getLineCount()); assertEquals(954, h.getNewStartLine()); assertEquals(7, h.getNewLineCount()); assertEquals(6, h.getLinesContext()); assertEquals(1, h.getOldImage().getLinesAdded()); assertEquals(1, h.getOldImage().getLinesDeleted()); assertEquals(3035, h.endOffset); } } public void testParse_NoBinary() throws IOException { final Patch p = parseTestPatchFile(); assertEquals(5, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); for (int i = 0; i < 4; i++) { final FileHeader fh = p.getFiles().get(i); assertSame(FileHeader.ChangeType.ADD, fh.getChangeType()); assertNotNull(fh.getOldId()); assertNotNull(fh.getNewId()); assertEquals("0000000", fh.getOldId().name()); assertSame(FileMode.MISSING, fh.getOldMode()); assertSame(FileMode.REGULAR_FILE, fh.getNewMode()); assertTrue(fh.getNewName().startsWith( "org.spearce.egit.ui/icons/toolbar/")); assertSame(FileHeader.PatchType.BINARY, fh.getPatchType()); assertTrue(fh.getHunks().isEmpty()); assertTrue(fh.hasMetaDataChanges()); assertNull(fh.getForwardBinaryHunk()); assertNull(fh.getReverseBinaryHunk()); } final FileHeader fh = p.getFiles().get(4); assertEquals("org.spearce.egit.ui/plugin.xml", fh.getNewName()); assertSame(FileHeader.ChangeType.MODIFY, fh.getChangeType()); assertSame(FileHeader.PatchType.UNIFIED, fh.getPatchType()); assertFalse(fh.hasMetaDataChanges()); assertEquals("ee8a5a0", fh.getNewId().name()); assertNull(fh.getForwardBinaryHunk()); assertNull(fh.getReverseBinaryHunk()); assertEquals(1, fh.getHunks().size()); assertEquals(272, fh.getHunks().get(0).getOldImage().getStartLine()); } public void testParse_GitBinaryLiteral() throws IOException { final Patch p = parseTestPatchFile(); final int[] binsizes = { 359, 393, 372, 404 }; assertEquals(5, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); for (int i = 0; i < 4; i++) { final FileHeader fh = p.getFiles().get(i); assertSame(FileHeader.ChangeType.ADD, fh.getChangeType()); assertNotNull(fh.getOldId()); assertNotNull(fh.getNewId()); assertEquals(ObjectId.zeroId().name(), fh.getOldId().name()); assertSame(FileMode.REGULAR_FILE, fh.getNewMode()); assertTrue(fh.getNewName().startsWith( "org.spearce.egit.ui/icons/toolbar/")); assertSame(FileHeader.PatchType.GIT_BINARY, fh.getPatchType()); assertTrue(fh.getHunks().isEmpty()); assertTrue(fh.hasMetaDataChanges()); final BinaryHunk fwd = fh.getForwardBinaryHunk(); final BinaryHunk rev = fh.getReverseBinaryHunk(); assertNotNull(fwd); assertNotNull(rev); assertEquals(binsizes[i], fwd.getSize()); assertEquals(0, rev.getSize()); assertSame(fh, fwd.getFileHeader()); assertSame(fh, rev.getFileHeader()); assertSame(BinaryHunk.Type.LITERAL_DEFLATED, fwd.getType()); assertSame(BinaryHunk.Type.LITERAL_DEFLATED, rev.getType()); } final FileHeader fh = p.getFiles().get(4); assertEquals("org.spearce.egit.ui/plugin.xml", fh.getNewName()); assertSame(FileHeader.ChangeType.MODIFY, fh.getChangeType()); assertSame(FileHeader.PatchType.UNIFIED, fh.getPatchType()); assertFalse(fh.hasMetaDataChanges()); assertEquals("ee8a5a0", fh.getNewId().name()); assertNull(fh.getForwardBinaryHunk()); assertNull(fh.getReverseBinaryHunk()); assertEquals(1, fh.getHunks().size()); assertEquals(272, fh.getHunks().get(0).getOldImage().getStartLine()); } public void testParse_GitBinaryDelta() throws IOException { final Patch p = parseTestPatchFile(); assertEquals(1, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); final FileHeader fh = p.getFiles().get(0); assertTrue(fh.getNewName().startsWith("zero.bin")); assertSame(FileHeader.ChangeType.MODIFY, fh.getChangeType()); assertSame(FileHeader.PatchType.GIT_BINARY, fh.getPatchType()); assertSame(FileMode.REGULAR_FILE, fh.getNewMode()); assertNotNull(fh.getOldId()); assertNotNull(fh.getNewId()); assertEquals("08e7df176454f3ee5eeda13efa0adaa54828dfd8", fh.getOldId() .name()); assertEquals("d70d8710b6d32ff844af0ee7c247e4b4b051867f", fh.getNewId() .name()); assertTrue(fh.getHunks().isEmpty()); assertFalse(fh.hasMetaDataChanges()); final BinaryHunk fwd = fh.getForwardBinaryHunk(); final BinaryHunk rev = fh.getReverseBinaryHunk(); assertNotNull(fwd); assertNotNull(rev); assertEquals(12, fwd.getSize()); assertEquals(11, rev.getSize()); assertSame(fh, fwd.getFileHeader()); assertSame(fh, rev.getFileHeader()); assertSame(BinaryHunk.Type.DELTA_DEFLATED, fwd.getType()); assertSame(BinaryHunk.Type.DELTA_DEFLATED, rev.getType()); assertEquals(496, fh.endOffset); } public void testParse_FixNoNewline() throws IOException { final Patch p = parseTestPatchFile(); assertEquals(1, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); final FileHeader f = p.getFiles().get(0); assertEquals("a", f.getNewName()); assertEquals(252, f.startOffset); assertEquals("2e65efe", f.getOldId().name()); assertEquals("f2ad6c7", f.getNewId().name()); assertSame(FileHeader.PatchType.UNIFIED, f.getPatchType()); assertSame(FileMode.REGULAR_FILE, f.getOldMode()); assertSame(FileMode.REGULAR_FILE, f.getNewMode()); assertEquals(1, f.getHunks().size()); { final HunkHeader h = f.getHunks().get(0); assertSame(f, h.getFileHeader()); assertEquals(317, h.startOffset); assertEquals(1, h.getOldImage().getStartLine()); assertEquals(1, h.getOldImage().getLineCount()); assertEquals(1, h.getNewStartLine()); assertEquals(1, h.getNewLineCount()); assertEquals(0, h.getLinesContext()); assertEquals(1, h.getOldImage().getLinesAdded()); assertEquals(1, h.getOldImage().getLinesDeleted()); assertSame(f.getOldId(), h.getOldImage().getId()); assertEquals(363, h.endOffset); } } public void testParse_AddNoNewline() throws IOException { final Patch p = parseTestPatchFile(); assertEquals(1, p.getFiles().size()); assertTrue(p.getErrors().isEmpty()); final FileHeader f = p.getFiles().get(0); assertEquals("a", f.getNewName()); assertEquals(256, f.startOffset); assertEquals("f2ad6c7", f.getOldId().name()); assertEquals("c59d9b6", f.getNewId().name()); assertSame(FileHeader.PatchType.UNIFIED, f.getPatchType()); assertSame(FileMode.REGULAR_FILE, f.getOldMode()); assertSame(FileMode.REGULAR_FILE, f.getNewMode()); assertEquals(1, f.getHunks().size()); { final HunkHeader h = f.getHunks().get(0); assertSame(f, h.getFileHeader()); assertEquals(321, h.startOffset); assertEquals(1, h.getOldImage().getStartLine()); assertEquals(1, h.getOldImage().getLineCount()); assertEquals(1, h.getNewStartLine()); assertEquals(1, h.getNewLineCount()); assertEquals(0, h.getLinesContext()); assertEquals(1, h.getOldImage().getLinesAdded()); assertEquals(1, h.getOldImage().getLinesDeleted()); assertSame(f.getOldId(), h.getOldImage().getId()); assertEquals(367, h.endOffset); } } private Patch parseTestPatchFile() throws IOException { final String patchFile = getName() + ".patch"; final InputStream in = getClass().getResourceAsStream(patchFile); if (in == null) { fail("No " + patchFile + " test vector"); return null; // Never happens } try { final Patch p = new Patch(); p.parse(in); return p; } finally { in.close(); } } } 3'>153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
/*
* $Id$
* ============================================================================
* The Apache Software License, Version 1.1
* ============================================================================
*
* Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by the Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "FOP" and "Apache Software Foundation" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache", nor may
* "Apache" appear in their name, without prior written permission of the
* Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
* DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Apache Software Foundation and was originally created by
* James Tauber <jtauber@jtauber.com>. For more information on the Apache
* Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.fop.pdf;
// Java
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
// Apache libs
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.commons.io.IOUtil;
// FOP
import org.apache.fop.fonts.CIDFont;
import org.apache.fop.fonts.CustomFont;
import org.apache.fop.fonts.Typeface;
import org.apache.fop.fonts.FontDescriptor;
import org.apache.fop.fonts.FontMetrics;
import org.apache.fop.fonts.FontType;
import org.apache.fop.fonts.LazyFont;
import org.apache.fop.fonts.MultiByteFont;
import org.apache.fop.fonts.truetype.FontFileReader;
import org.apache.fop.fonts.truetype.TTFSubSetFile;
import org.apache.fop.fonts.type1.PFBData;
import org.apache.fop.fonts.type1.PFBParser;
/**
* This class provides method to create and register PDF objects.
*/
public class PDFFactory {
private PDFDocument document;
/**
* Creates a new PDFFactory.
* @param document the parent PDFDocument needed to register the generated
* objects
*/
public PDFFactory(PDFDocument document) {
this.document = document;
}
/**
* Returns the parent PDFDocument associated with this factory.
* @return PDFDocument the parent PDFDocument
*/
public final PDFDocument getDocument() {
return this.document;
}
/* ========================= structure objects ========================= */
/**
* Make a /Catalog (Root) object. This object is written in
* the trailer.
*
* @param pages the pages pdf object that the root points to
* @return the new pdf root object for this document
*/
public PDFRoot makeRoot(PDFPages pages) {
//Make a /Pages object. This object is written in the trailer.
PDFRoot pdfRoot = new PDFRoot(++this.document.objectcount, pages);
getDocument().addTrailerObject(pdfRoot);
return pdfRoot;
}
/**
* Make a /Pages object. This object is written in the trailer.
*
* @return a new PDF Pages object for adding pages to
*/
public PDFPages makePages() {
PDFPages pdfPages = new PDFPages(++this.document.objectcount);
getDocument().addTrailerObject(pdfPages);
return pdfPages;
}
/**
* Make a /Resources object. This object is written in the trailer.
*
* @return a new PDF resources object
*/
public PDFResources makeResources() {
PDFResources pdfResources = new PDFResources(++this.document.objectcount);
getDocument().addTrailerObject(pdfResources);
return pdfResources;
}
/**
* make an /Info object
*
* @param prod string indicating application producing the PDF
* @return the created /Info object
*/
protected PDFInfo makeInfo(String prod) {
/*
* create a PDFInfo with the next object number and add to
* list of objects
*/
PDFInfo pdfInfo = new PDFInfo();
// set the default producer
pdfInfo.setProducer(prod);
getDocument().registerObject(pdfInfo);
return pdfInfo;
}
/**
* Make a /Page object. The page is assigned an object number immediately
* so references can already be made. The page must be added to the
* PDFDocument later using addObject().
*
* @param resources resources object to use
* @param pagewidth width of the page in points
* @param pageheight height of the page in points
*
* @return the created /Page object
*/
public PDFPage makePage(PDFResources resources,
int pagewidth, int pageheight) {
/*
* create a PDFPage with the next object number, the given
* resources, contents and dimensions
*/
PDFPage page = new PDFPage(resources,
pagewidth, pageheight);
getDocument().assignObjectNumber(page);
getDocument().getPages().addPage(page);
return page;
}
/* ========================= functions ================================= */
/**
* Make a Type 0 sampled function
*
* @param theDomain List objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange List objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theSize A List object of Integer objects.
* This is the number of samples in each input dimension.
* I can't imagine there being more or less than two input dimensions,
* so maybe this should be an array of length 2.
*
* See page 265 of the PDF 1.3 Spec.
* @param theBitsPerSample An int specifying the number of bits user
* to represent each sample value.
* Limited to 1,2,4,8,12,16,24 or 32.
* See page 265 of the 1.3 PDF Spec.
* @param theOrder The order of interpolation between samples.
* Default is 1 (one). Limited
* to 1 (one) or 3, which means linear or cubic-spline interpolation.
*
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theEncode List objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theDecode List objects of Double objects.
* This is a linear mapping of sample values into the range.
* The default is just the range.
*
* This attribute is optional.
* Read about it on page 265 of the PDF 1.3 spec.
* @param theFunctionDataStream The sample values that specify
* the function are provided in a stream.
*
* This is optional, but is almost always used.
*
* Page 265 of the PDF 1.3 spec has more.
* @param theFilter This is a vector of String objects which
* are the various filters that have are to be
* applied to the stream to make sense of it.
* Order matters, so watch out.
*
* This is not documented in the Function section of the PDF 1.3 spec,
* it was deduced from samples that this is sometimes used, even if we may never
* use it in FOP. It is added for completeness sake.
* @param theFunctionType This is the type of function (0,2,3, or 4).
* It should be 0 as this is the constructor for sampled functions.
* @return the PDF function that was created
*/
public PDFFunction makeFunction(int theFunctionType, List theDomain,
List theRange, List theSize,
int theBitsPerSample, int theOrder,
List theEncode, List theDecode,
StringBuffer theFunctionDataStream,
List theFilter) {
// Type 0 function
PDFFunction function = new PDFFunction(theFunctionType, theDomain,
theRange, theSize,
theBitsPerSample, theOrder,
theEncode, theDecode,
theFunctionDataStream,
theFilter);
PDFFunction oldfunc = getDocument().findFunction(function);
if (oldfunc == null) {
getDocument().registerObject(function);
} else {
function = oldfunc;
}
return (function);
}
/**
* make a type Exponential interpolation function
* (for shading usually)
*
* @param theDomain List objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange List of Doubles that is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theCZero This is a vector of Double objects which defines the function result
* when x=0.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theCOne This is a vector of Double objects which defines the function result
* when x=1.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theInterpolationExponentN This is the inerpolation exponent.
*
* This attribute is required.
* PDF Spec page 268
* @param theFunctionType The type of the function, which should be 2.
* @return the PDF function that was created
*/
public PDFFunction makeFunction(int theFunctionType, List theDomain,
List theRange, List theCZero,
List theCOne,
double theInterpolationExponentN) { // type 2
PDFFunction function = new PDFFunction(theFunctionType, theDomain,
theRange, theCZero, theCOne,
theInterpolationExponentN);
PDFFunction oldfunc = getDocument().findFunction(function);
if (oldfunc == null) {
getDocument().registerObject(function);
} else {
function = oldfunc;
}
return (function);
}
/**
* Make a Type 3 Stitching function
*
* @param theDomain List objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange List objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theFunctions An List of the PDFFunction objects
* that the stitching function stitches.
*
* This attributed is required.
* It is described on page 269 of the PDF spec.
* @param theBounds This is a vector of Doubles representing
* the numbers that, in conjunction with Domain
* define the intervals to which each function from
* the 'functions' object applies. It must be in
* order of increasing magnitude, and each must be
* within Domain.
*
* It basically sets how much of the gradient each function handles.
*
* This attributed is required.
* It's described on page 269 of the PDF 1.3 spec.
* @param theEncode List objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is required.
*
* See page 270 in the PDF 1.3 spec.
* @param theFunctionType This is the function type. It should be 3,
* for a stitching function.
* @return the PDF function that was created
*/
public PDFFunction makeFunction(int theFunctionType, List theDomain,
List theRange, List theFunctions,
List theBounds,
List theEncode) {
// Type 3
PDFFunction function = new PDFFunction(theFunctionType, theDomain,
theRange, theFunctions,
theBounds, theEncode);
PDFFunction oldfunc = getDocument().findFunction(function);
if (oldfunc == null) {
getDocument().registerObject(function);
} else {
function = oldfunc;
}
return (function);
}
/**
* make a postscript calculator function
*
* @param theNumber the PDF object number
* @param theFunctionType the type of function to make
* @param theDomain the domain values
* @param theRange the range values of the function
* @param theFunctionDataStream a string containing the pdf drawing
* @return the PDF function that was created
*/
public PDFFunction makeFunction(int theNumber, int theFunctionType,
List theDomain, List theRange,
StringBuffer theFunctionDataStream) {
// Type 4
PDFFunction function = new PDFFunction(theFunctionType, theDomain,
theRange,
theFunctionDataStream);
PDFFunction oldfunc = getDocument().findFunction(function);
if (oldfunc == null) {
getDocument().registerObject(function);
} else {
function = oldfunc;
}
return (function);
}
/* ========================= shadings ================================== */
/**
* make a function based shading object
*
* @param res the PDF resource context to add the shading, may be null
* @param theShadingType The type of shading object, which should be 1 for function
* based shading.
* @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
* @param theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox List of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Whether or not to anti-alias.
* @param theDomain Optional vector of Doubles specifying the domain.
* @param theMatrix List of Doubles specifying the matrix.
* If it's a pattern, then the matrix maps it to pattern space.
* If it's a shading, then it maps it to current user space.
* It's optional, the default is the identity matrix
* @param theFunction The PDF Function that maps an (x,y) location to a color
* @return the PDF shading that was created
*/
public PDFShading makeShading(PDFResourceContext res, int theShadingType,
PDFColorSpace theColorSpace,
List theBackground, List theBBox,
boolean theAntiAlias, List theDomain,
List theMatrix,
PDFFunction theFunction) {
// make Shading of Type 1
PDFShading shading = new PDFShading(theShadingType,
theColorSpace, theBackground,
theBBox, theAntiAlias, theDomain,
theMatrix, theFunction);
PDFShading oldshad = getDocument().findShading(shading);
if (oldshad == null) {
getDocument().registerObject(shading);
} else {
shading = oldshad;
}
// add this shading to resources
if (res != null) {
res.getPDFResources().addShading(shading);
} else {
getDocument().getResources().addShading(shading);
}
return (shading);
}
/**
* Make an axial or radial shading object.
*
* @param res the PDF resource context to add the shading, may be null
* @param theShadingType 2 or 3 for axial or radial shading
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox List of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theCoords List of four (type 2) or 6 (type 3) Double
* @param theDomain List of Doubles specifying the domain
* @param theFunction the Stitching (PDFfunction type 3) function,
* even if it's stitching a single function
* @param theExtend List of Booleans of whether to extend the
* start and end colors past the start and end points
* The default is [false, false]
* @return the PDF shading that was created
*/
public PDFShading makeShading(PDFResourceContext res, int theShadingType,
PDFColorSpace theColorSpace,
List theBackground, List theBBox,
boolean theAntiAlias, List theCoords,
List theDomain, PDFFunction theFunction,
List theExtend) {
// make Shading of Type 2 or 3
PDFShading shading = new PDFShading(theShadingType,
theColorSpace, theBackground,
theBBox, theAntiAlias, theCoords,
theDomain, theFunction,
theExtend);
PDFShading oldshad = getDocument().findShading(shading);
if (oldshad == null) {
getDocument().registerObject(shading);
} else {
shading = oldshad;
}
if (res != null) {
res.getPDFResources().addShading(shading);
} else {
getDocument().getResources().addShading(shading);
}
return (shading);
}
/**
* Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
* shading object
*
* @param res the PDF resource context to add the shading, may be null
* @param theShadingType 4, 6, or 7 depending on whether it's
* Free-form gouraud-shaded triangle meshes, coons patch meshes,
* or tensor product patch meshes, respectively.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox List of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
* @param theBitsPerComponent 1,2,4,8,12, and 16
* @param theBitsPerFlag 2,4,8.
* @param theDecode List of Doubles see PDF 1.3 spec pages 303 to 312.
* @param theFunction the PDFFunction
* @return the PDF shading that was created
*/
public PDFShading makeShading(PDFResourceContext res, int theShadingType,
PDFColorSpace theColorSpace,
List theBackground, List theBBox,
boolean theAntiAlias,
int theBitsPerCoordinate,
int theBitsPerComponent,
int theBitsPerFlag, List theDecode,
PDFFunction theFunction) {
// make Shading of type 4,6 or 7
PDFShading shading = new PDFShading(theShadingType,
theColorSpace, theBackground,
theBBox, theAntiAlias,
theBitsPerCoordinate,
theBitsPerComponent,
theBitsPerFlag, theDecode,
theFunction);
PDFShading oldshad = getDocument().findShading(shading);
if (oldshad == null) {
getDocument().registerObject(shading);
} else {
shading = oldshad;
}
if (res != null) {
res.getPDFResources().addShading(shading);
} else {
getDocument().getResources().addShading(shading);
}
return (shading);
}
/**
* make a Lattice-Form Gouraud mesh shading object
*
* @param res the PDF resource context to add the shading, may be null
* @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
* without spaces. "Shading1" or "Sh1" are good examples.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox List of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
* @param theBitsPerComponent 1,2,4,8,12,24,32
* @param theDecode List of Doubles. See page 305 in PDF 1.3 spec.
* @param theVerticesPerRow number of vertices in each "row" of the lattice.
* @param theFunction The PDFFunction that's mapped on to this shape
* @return the PDF shading that was created
*/
public PDFShading makeShading(PDFResourceContext res, int theShadingType,
PDFColorSpace theColorSpace,
List theBackground, List theBBox,
boolean theAntiAlias,
int theBitsPerCoordinate,
int theBitsPerComponent, List theDecode,
int theVerticesPerRow,
PDFFunction theFunction) {
// make shading of Type 5
PDFShading shading = new PDFShading(theShadingType,
theColorSpace, theBackground,
theBBox, theAntiAlias,
theBitsPerCoordinate,
theBitsPerComponent, theDecode,
theVerticesPerRow, theFunction);
PDFShading oldshad = getDocument().findShading(shading);
if (oldshad == null) {
getDocument().registerObject(shading);
} else {
shading = oldshad;
}
if (res != null) {
res.getPDFResources().addShading(shading);
} else {
getDocument().getResources().addShading(shading);
}
return (shading);
}
/* ========================= patterns ================================== */
/**
* Make a tiling pattern
*
* @param res the PDF resource context to add the shading, may be null
* @param thePatternType the type of pattern, which is 1 for tiling.
* @param theResources the resources associated with this pattern
* @param thePaintType 1 or 2, colored or uncolored.
* @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
* @param theBBox List of Doubles: The pattern cell bounding box
* @param theXStep horizontal spacing
* @param theYStep vertical spacing
* @param theMatrix Optional List of Doubles transformation matrix
* @param theXUID Optional vector of Integers that uniquely identify the pattern
* @param thePatternDataStream The stream of pattern data to be tiled.
* @return the PDF pattern that was created
*/
public PDFPattern makePattern(PDFResourceContext res, int thePatternType, // 1
PDFResources theResources, int thePaintType, int theTilingType,
List theBBox, double theXStep,
double theYStep, List theMatrix,
List theXUID, StringBuffer thePatternDataStream) {
// PDFResources theResources
PDFPattern pattern = new PDFPattern(theResources, 1,
thePaintType, theTilingType,
theBBox, theXStep, theYStep,
theMatrix, theXUID,
thePatternDataStream);
PDFPattern oldpatt = getDocument().findPattern(pattern);
if (oldpatt == null) {
getDocument().registerObject(pattern);
} else {
pattern = oldpatt;
}
if (res != null) {
res.getPDFResources().addPattern(pattern);
} else {
getDocument().getResources().addPattern(pattern);
}
return (pattern);
}
/**
* Make a smooth shading pattern
*
* @param res the PDF resource context to add the shading, may be null
* @param thePatternType the type of the pattern, which is 2, smooth shading
* @param theShading the PDF Shading object that comprises this pattern
* @param theXUID optional:the extended unique Identifier if used.
* @param theExtGState optional: the extended graphics state, if used.
* @param theMatrix Optional:List of Doubles that specify the matrix.
* @return the PDF pattern that was created
*/
public PDFPattern makePattern(PDFResourceContext res,
int thePatternType, PDFShading theShading,
List theXUID, StringBuffer theExtGState,
List theMatrix) {
PDFPattern pattern = new PDFPattern(2, theShading,
theXUID, theExtGState, theMatrix);
PDFPattern oldpatt = getDocument().findPattern(pattern);
if (oldpatt == null) {
getDocument().registerObject(pattern);
} else {
pattern = oldpatt;
}
if (res != null) {
res.getPDFResources().addPattern(pattern);
} else {
getDocument().getResources().addPattern(pattern);
}
return (pattern);
}
/**
* Make a gradient
*
* @param res the PDF resource context to add the shading, may be null
* @param radial if true a radial gradient will be created
* @param theColorspace the colorspace of the gradient
* @param theColors the list of colors for the gradient
* @param theBounds the list of bounds associated with the colors
* @param theCoords the coordinates for the gradient
* @return the PDF pattern that was created
*/
public PDFPattern makeGradient(PDFResourceContext res, boolean radial,
PDFColorSpace theColorspace,
List theColors, List theBounds,
List theCoords) {
PDFShading myShad;
PDFFunction myfunky;
PDFFunction myfunc;
List theCzero;
List theCone;
PDFPattern myPattern;
//PDFColorSpace theColorSpace;
double interpolation = (double)1.000;
List theFunctions = new java.util.ArrayList();
int currentPosition;
int lastPosition = theColors.size() - 1;
// if 5 elements, the penultimate element is 3.
// do not go beyond that, because you always need
// to have a next color when creating the function.
for (currentPosition = 0; currentPosition < lastPosition;
currentPosition++) { // for every consecutive color pair
PDFColor currentColor =
(PDFColor)theColors.get(currentPosition);
PDFColor nextColor = (PDFColor)theColors.get(currentPosition
+ 1);
// colorspace must be consistant
if (getDocument().getColorSpace()
!= currentColor.getColorSpace()) {
currentColor.setColorSpace(
getDocument().getColorSpace());
}
if (getDocument().getColorSpace()
!= nextColor.getColorSpace()) {
nextColor.setColorSpace(
getDocument().getColorSpace());
}
theCzero = currentColor.getVector();
theCone = nextColor.getVector();
myfunc = makeFunction(2, null, null, theCzero, theCone,
interpolation);
theFunctions.add(myfunc);
} // end of for every consecutive color pair
myfunky = makeFunction(3, null, null, theFunctions, theBounds,
null);
if (radial) {
if (theCoords.size() == 6) {
myShad = makeShading(res, 3, getDocument().getPDFColorSpace(),
null, null,
false, theCoords, null, myfunky,
null);
} else { // if the center x, center y, and radius specifiy
// the gradient, then assume the same center x, center y,
// and radius of zero for the other necessary component
List newCoords = new java.util.ArrayList();
newCoords.add(theCoords.get(0));
newCoords.add(theCoords.get(1));
newCoords.add(theCoords.get(2));
newCoords.add(theCoords.get(0));
newCoords.add(theCoords.get(1));
newCoords.add(new Double(0.0));
myShad = makeShading(res, 3, getDocument().getPDFColorSpace(),
null, null,
false, newCoords, null, myfunky,
null);
}
} else {
myShad = makeShading(res, 2, getDocument().getPDFColorSpace(),
null, null,
false, theCoords, null, myfunky,
null);
}
myPattern = makePattern(res, 2, myShad, null, null, null);
return (myPattern);
}
/* ========================= links ===================================== */
/**
* Make an internal link.
*
* @param rect the hotspot position in absolute coordinates
* @param page the target page reference value
* @param dest the position destination
* @return the new PDF link object
*/
public PDFLink makeLink(Rectangle2D rect, String page, String dest) {
PDFLink link = new PDFLink(rect);
getDocument().registerObject(link);
PDFGoTo gt = new PDFGoTo(page);
gt.setDestination(dest);
getDocument().addTrailerObject(gt);
PDFInternalLink internalLink = new PDFInternalLink(gt.referencePDF());
link.setAction(internalLink);
return link;
}
/**
* make a link object
*
* @param rect the clickable rectangle
* @param destination the destination file
* @param linkType the link type
* @param yoffset the yoffset on the page for an internal link
* @return the PDFLink object created
*/
public PDFLink makeLink(Rectangle2D rect, String destination,
int linkType, float yoffset) {
//PDFLink linkObject;
int index;
PDFLink link = new PDFLink(rect);
if (linkType == PDFLink.EXTERNAL) {
// check destination
if (destination.startsWith("http://")) {
PDFUri uri = new PDFUri(destination);
link.setAction(uri);
} else if (destination.endsWith(".pdf")) { // FileSpec
PDFGoToRemote remote = getGoToPDFAction(destination, null, -1);
link.setAction(remote);
} else if ((index = destination.indexOf(".pdf#page=")) > 0) {
//String file = destination.substring(0, index + 4);
int page = Integer.parseInt(destination.substring(index + 10));
PDFGoToRemote remote = getGoToPDFAction(destination, null, page);
link.setAction(remote);
} else if ((index = destination.indexOf(".pdf#dest=")) > 0) {
//String file = destination.substring(0, index + 4);
String dest = destination.substring(index + 10);
PDFGoToRemote remote = getGoToPDFAction(destination, dest, -1);
link.setAction(remote);
} else { // URI
PDFUri uri = new PDFUri(destination);
link.setAction(uri);
}
} else {
// linkType is internal
String goToReference = getGoToReference(destination, yoffset);
PDFInternalLink internalLink = new PDFInternalLink(goToReference);
link.setAction(internalLink);
}
PDFLink oldlink = getDocument().findLink(link);
if (oldlink == null) {
getDocument().registerObject(link);
} else {
link = oldlink;
}
return link;
}
private String getGoToReference(String destination, float yoffset) {
String goToReference = null;
PDFGoTo gt = new PDFGoTo(destination);
gt.setYPosition(yoffset);
PDFGoTo oldgt = getDocument().findGoTo(gt);
if (oldgt == null) {
getDocument().assignObjectNumber(gt);
getDocument().addTrailerObject(gt);
} else {
gt = oldgt;
}
goToReference = gt.referencePDF();
return goToReference;
}
/**
* Create and return a goto pdf document action.
* This creates a pdf files spec and pdf goto remote action.
* It also checks available pdf objects so it will not create an
* object if it already exists.
*
* @param file the pdf file name
* @param dest the remote name destination, may be null
* @param page the remote page number, -1 means not specified
* @return the pdf goto remote object
*/
private PDFGoToRemote getGoToPDFAction(String file, String dest, int page) {
PDFFileSpec fileSpec = new PDFFileSpec(file);
PDFFileSpec oldspec = getDocument().findFileSpec(fileSpec);
if (oldspec == null) {
getDocument().registerObject(fileSpec);
} else {
fileSpec = oldspec;
}
PDFGoToRemote remote;
if (dest == null && page == -1) {
remote = new PDFGoToRemote(fileSpec);
} else if (dest != null) {
remote = new PDFGoToRemote(fileSpec, dest);
} else {
remote = new PDFGoToRemote(fileSpec, page);
}
PDFGoToRemote oldremote = getDocument().findGoToRemote(remote);
if (oldremote == null) {
getDocument().registerObject(remote);
} else {
remote = oldremote;
}
return remote;
}
/**
* Make an outline object and add it to the given outline
*
* @param parent parent PDFOutline object which may be null
* @param label the title for the new outline object
* @param destination the reference string for the action to go to
* @param yoffset the yoffset on the destination page
* @return the new PDF outline object
*/
public PDFOutline makeOutline(PDFOutline parent, String label,
String destination, float yoffset) {
String goToRef = getGoToReference(destination, yoffset);
PDFOutline obj = new PDFOutline(label, goToRef);
if (parent != null) {
parent.addOutline(obj);
}
getDocument().registerObject(obj);
return obj;
}
/* ========================= fonts ===================================== */
/**
* make a /Encoding object
*
* @param encodingName character encoding scheme name
* @return the created /Encoding object
*/
public PDFEncoding makeEncoding(String encodingName) {
PDFEncoding encoding = new PDFEncoding(encodingName);
getDocument().registerObject(encoding);
return encoding;
}
/**
* make a Type1 /Font object
*
* @param fontname internal name to use for this font (eg "F1")
* @param basefont name of the base font (eg "Helvetica")
* @param encoding character encoding scheme used by the font
* @param metrics additional information about the font
* @param descriptor additional information about the font
* @return the created /Font object
*/
public PDFFont makeFont(String fontname, String basefont,
String encoding, FontMetrics metrics,
FontDescriptor descriptor) {
PDFFont preRegisteredfont = getDocument().findFont(fontname);
if (preRegisteredfont != null) {
return preRegisteredfont;
}
if (descriptor == null) {
PDFFont font = new PDFFont(fontname, FontType.TYPE1, basefont, encoding);
getDocument().registerObject(font);
return font;
} else {
FontType fonttype = metrics.getFontType();
PDFFontDescriptor pdfdesc = makeFontDescriptor(descriptor);
PDFFontNonBase14 font = null;
if (fonttype == FontType.TYPE0) {
/*
* Temporary commented out - customized CMaps
* isn't needed until /ToUnicode support is added
* PDFCMap cmap = new PDFCMap(++this.objectcount,
* "fop-ucs-H",
* new PDFCIDSystemInfo("Adobe",
* "Identity",
* 0));
* cmap.addContents();
* this.objects.add(cmap);
*/
font =
(PDFFontNonBase14)PDFFont.createFont(fontname, fonttype,
basefont,
"Identity-H");
} else {
font =
(PDFFontNonBase14)PDFFont.createFont(fontname, fonttype,
basefont, encoding);
}
getDocument().registerObject(font);
font.setDescriptor(pdfdesc);
if (fonttype == FontType.TYPE0) {
CIDFont cidMetrics;
if (metrics instanceof LazyFont) {
cidMetrics = (CIDFont)((LazyFont) metrics).getRealFont();
} else {
cidMetrics = (CIDFont)metrics;
}
PDFCIDSystemInfo sysInfo =
new PDFCIDSystemInfo(cidMetrics.getRegistry(),
cidMetrics.getOrdering(),
cidMetrics.getSupplement());
PDFCIDFont cidFont =
new PDFCIDFont(basefont,
cidMetrics.getCIDType(),
cidMetrics.getDefaultWidth(),
getSubsetWidths(cidMetrics), sysInfo,
(PDFCIDFontDescriptor)pdfdesc);
getDocument().registerObject(cidFont);
((PDFFontType0)font).setDescendantFonts(cidFont);
} else {
int firstChar = 0;
int lastChar = 255;
if (metrics instanceof CustomFont) {
CustomFont cf = (CustomFont)metrics;
firstChar = cf.getFirstChar();
lastChar = cf.getLastChar();
}
font.setWidthMetrics(firstChar,
lastChar,
makeArray(metrics.getWidths()));
}
return font;
}
}
public PDFWArray getSubsetWidths(CIDFont cidFont) {
// Create widths for reencoded chars
PDFWArray warray = new PDFWArray();
int[] tmpWidth = new int[cidFont.usedGlyphsCount];
for (int i = 0; i < cidFont.usedGlyphsCount; i++) {
Integer nw = (Integer)cidFont.usedGlyphsIndex.get(new Integer(i));
int nwx = (nw == null) ? 0 : nw.intValue();
tmpWidth[i] = cidFont.width[nwx];
}
warray.addEntry(0, tmpWidth);
return warray;
}
/**
* make a /FontDescriptor object
*
* @param desc the font descriptor
* @return the new PDF font descriptor
*/
public PDFFontDescriptor makeFontDescriptor(FontDescriptor desc) {
PDFFontDescriptor descriptor = null;
if (desc.getFontType() == FontType.TYPE0) {
// CID Font
descriptor = new PDFCIDFontDescriptor(desc.getFontName(),
desc.getFontBBox(),
desc.getCapHeight(),
desc.getFlags(),
desc.getItalicAngle(),
desc.getStemV(), null);
} else {
// Create normal FontDescriptor
descriptor = new PDFFontDescriptor(desc.getFontName(),
desc.getAscender(),
desc.getDescender(),
desc.getCapHeight(),
desc.getFlags(),
new PDFRectangle(desc.getFontBBox()),
desc.getStemV(),
desc.getItalicAngle());
}
getDocument().registerObject(descriptor);
// Check if the font is embeddable
if (desc.isEmbeddable()) {
AbstractPDFStream stream = makeFontFile(desc);
if (stream != null) {
descriptor.setFontFile(desc.getFontType(), stream);
getDocument().registerObject(stream);
}
}
return descriptor;
}
/**
* Embeds a font.
* @param desc FontDescriptor of the font.
* @return PDFStream The embedded font file
*/
public AbstractPDFStream makeFontFile(FontDescriptor desc) {
if (desc.getFontType() == FontType.OTHER) {
throw new IllegalArgumentException("Trying to embed unsupported font type: "
+ desc.getFontType());
}
Typeface tempFont;
if (desc instanceof LazyFont) {
tempFont = ((LazyFont)desc).getRealFont();
} else {
tempFont = (Typeface)desc;
}
if (!(tempFont instanceof CustomFont)) {
throw new IllegalArgumentException(
"FontDescriptor must be instance of CustomFont, but is a "
+ desc.getClass().getName());
}
CustomFont font = (CustomFont)tempFont;
InputStream in = null;
try {
// Get file first
if (font.getEmbedFileName() != null) {
try {
in = getDocument().resolveURI(font.getEmbedFileName());
} catch (Exception e) {
getDocument().getLogger().error("Failed to embed fontfile: "
+ font.getEmbedFileName()
+ "(" + e.getMessage() + ")");
}
}
// Get resource
if (in == null && font.getEmbedResourceName() != null) {
try {
in = new java.io.BufferedInputStream(
this.getClass().getResourceAsStream(
font.getEmbedResourceName()));
} catch (Exception e) {
getDocument().getLogger().error(
"Failed to embed fontresource: "
+ font.getEmbedResourceName()
+ "(" + e.getMessage() + ")");
}
}
if (in == null) {
return null;
} else {
try {
AbstractPDFStream embeddedFont;
if (desc.getFontType() == FontType.TYPE0) {
MultiByteFont mbfont = (MultiByteFont)font;
FontFileReader reader = new FontFileReader(in);
TTFSubSetFile subset = new TTFSubSetFile();
ContainerUtil.enableLogging(subset,
getDocument().getLogger().getChildLogger("fonts"));
byte[] subsetFont = subset.readFont(reader,
mbfont.getTTCName(), mbfont.getUsedGlyphs());
// Only TrueType CID fonts are supported now
embeddedFont = new PDFTTFStream(subsetFont.length);
((PDFTTFStream)embeddedFont).setData(subsetFont, subsetFont.length);
} else if (desc.getFontType() == FontType.TYPE1) {
PFBParser parser = new PFBParser();
PFBData pfb = parser.parsePFB(in);
embeddedFont = new PDFT1Stream();
((PDFT1Stream)embeddedFont).setData(pfb);
} else {
byte[] file = IOUtil.toByteArray(in);
embeddedFont = new PDFTTFStream(file.length);
((PDFTTFStream)embeddedFont).setData(file, file.length);
}
/*
embeddedFont.getFilterList().addFilter("flate");
if (getDocument().isEncryptionActive()) {
getDocument().applyEncryption(embeddedFont);
} else {
embeddedFont.getFilterList().addFilter("ascii-85");
}*/
return embeddedFont;
} finally {
in.close();
}
}
} catch (IOException ioe) {
getDocument().getLogger().error(
"Failed to embed font [" + desc + "] "
+ desc.getFontName(), ioe);
return (PDFStream) null;
}
}
/* ========================= streams =================================== */
/**
* Make a stream object
*
* @param type the type of stream to be created
* @param add if true then the stream will be added immediately
* @return the stream object created
*/
public PDFStream makeStream(String type, boolean add) {
// create a PDFStream with the next object number
// and add it to the list of objects
PDFStream obj = new PDFStream();
obj.setDocument(getDocument());
obj.getFilterList().addDefaultFilters(
getDocument().getFilterMap(),
type);
if (add) {
getDocument().registerObject(obj);
}
//getDocument().applyEncryption(obj);
return obj;
}
/**
* Create a PDFICCStream
* @see PDFXObject
* @see org.apache.fop.image.JpegImage
* @see org.apache.fop.pdf.PDFColorSpace
* @return the new PDF ICC stream object
*/
public PDFICCStream makePDFICCStream() {
PDFICCStream iccStream = new PDFICCStream();
iccStream.getFilterList().addDefaultFilters(
getDocument().getFilterMap(),
PDFFilterList.CONTENT_FILTER);
getDocument().registerObject(iccStream);
//getDocument().applyEncryption(iccStream);
return iccStream;
}
/* ========================= misc. objects ============================= */
/**
* make an Array object (ex. Widths array for a font)
*
* @param values the int array values
* @return the PDF Array with the int values
*/
public PDFArray makeArray(int[] values) {
PDFArray array = new PDFArray(values);
getDocument().registerObject(array);
return array;
}
/**
* make an ExtGState for extra graphics options
* This tries to find a GState that will setup the correct values
* for the current context. If there is no suitable GState it will
* create a new one.
*
* @param settings the settings required by the caller
* @param current the current GState of the current PDF context
* @return a PDF GState, either an existing GState or a new one
*/
public PDFGState makeGState(Map settings, PDFGState current) {
// try to locate a gstate that has all the settings
// or will inherit from the current gstate
// compare "DEFAULT + settings" with "current + each gstate"
PDFGState wanted = new PDFGState();
wanted.addValues(PDFGState.DEFAULT);
wanted.addValues(settings);
PDFGState existing = getDocument().findGState(wanted, current);
if (existing != null) {
return existing;
}
PDFGState gstate = new PDFGState();
gstate.addValues(settings);
getDocument().registerObject(gstate);
return gstate;
}
/**
* Make an annotation list object
*
* @return the annotation list object created
*/
public PDFAnnotList makeAnnotList() {
PDFAnnotList obj = new PDFAnnotList();
getDocument().assignObjectNumber(obj);
return obj;
}
}