1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
|
/*
* Copyright 2003 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Image;
import com.lowagie.text.ExceptionConverter;
class PdfStamperImp extends PdfWriter {
HashMap readers2intrefs = new HashMap();
HashMap readers2file = new HashMap();
RandomAccessFileOrArray file;
PdfReader reader;
IntHashtable myXref = new IntHashtable();
/** Integer(page number) -> PageStamp */
HashMap pagesToContent = new HashMap();
boolean closed = false;
/** Holds value of property rotateContents. */
private boolean rotateContents = true;
protected AcroFields acroFields;
protected boolean flat = false;
protected boolean flatFreeText = false;
protected int namePtr[] = {0};
protected boolean namedAsNames;
protected List newBookmarks;
protected HashSet partialFlattening = new HashSet();
protected boolean useVp = false;
protected int vp = 0;
protected HashMap fieldTemplates = new HashMap();
protected boolean fieldsAdded = false;
protected int sigFlags = 0;
protected boolean append;
protected IntHashtable marked;
protected int initialXrefSize;
protected PdfAction openAction;
/** Creates new PdfStamperImp.
* @param reader the read PDF
* @param os the output destination
* @param pdfVersion the new pdf version or '\0' to keep the same version as the original
* document
* @param append
* @throws DocumentException on error
* @throws IOException
*/
PdfStamperImp(PdfReader reader, OutputStream os, char pdfVersion, boolean append) throws DocumentException, IOException {
super(new PdfDocument(), os);
if (reader.isTampered())
throw new DocumentException("The original document was reused. Read it again from file.");
reader.setTampered(true);
this.reader = reader;
file = reader.getSafeFile();
this.append = append;
if (append) {
if (reader.isRebuilt())
throw new DocumentException("Append mode requires a document without errors even if recovery was possible.");
if (reader.isEncrypted())
crypto = new PdfEncryption(reader.getDecrypt());
HEADER = getISOBytes("\n");
file.reOpen();
byte buf[] = new byte[8192];
int n;
while ((n = file.read(buf)) > 0)
this.os.write(buf, 0, n);
file.close();
prevxref = reader.getLastXref();
reader.setAppendable(true);
}
else {
if (pdfVersion == 0)
super.setPdfVersion(reader.getPdfVersion());
else
super.setPdfVersion(pdfVersion);
}
super.open();
pdf.addWriter(this);
if (append) {
body.setRefnum(reader.getXrefSize());
marked = new IntHashtable();
if (reader.isNewXrefType())
fullCompression = true;
if (reader.isHybridXref())
fullCompression = false;
}
initialXrefSize = reader.getXrefSize();
}
void close(HashMap moreInfo) throws DocumentException, IOException {
if (closed)
return;
if (useVp) {
reader.setViewerPreferences(vp);
markUsed(reader.getTrailer().get(PdfName.ROOT));
}
if (flat)
flatFields();
if (flatFreeText)
flatFreeTextFields();
addFieldResources();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(reader.getCatalog().get(PdfName.ACROFORM), reader.getCatalog());
if (acroFields != null && acroFields.getXfa().isChanged()) {
markUsed(acroForm);
if (!flat)
acroFields.getXfa().setXfa(this);
}
if (sigFlags != 0) {
if (acroForm != null) {
acroForm.put(PdfName.SIGFLAGS, new PdfNumber(sigFlags));
markUsed(acroForm);
}
}
closed = true;
addSharedObjectsToBody();
setOutlines();
setJavaScript();
addFileAttachments();
if (openAction != null) {
reader.getCatalog().put(PdfName.OPENACTION, openAction);
}
// if there is XMP data to add: add it
if (xmpMetadata != null) {
PdfDictionary catalog = reader.getCatalog();
PdfStream xmp = new PdfStream(xmpMetadata);
xmp.put(PdfName.TYPE, PdfName.METADATA);
xmp.put(PdfName.SUBTYPE, PdfName.XML);
catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference());
markUsed(catalog);
}
PRIndirectReference iInfo = null;
try {
file.reOpen();
alterContents();
iInfo = (PRIndirectReference)reader.trailer.get(PdfName.INFO);
int skip = -1;
if (iInfo != null)
skip = iInfo.getNumber();
int rootN = ((PRIndirectReference)reader.trailer.get(PdfName.ROOT)).getNumber();
if (append) {
int keys[] = marked.getKeys();
for (int k = 0; k < keys.length; ++k) {
int j = keys[k];
PdfObject obj = reader.getPdfObjectRelease(j);
if (obj != null && skip != j && j < initialXrefSize) {
addToBody(obj, j, j != rootN);
}
}
for (int k = initialXrefSize; k < reader.getXrefSize(); ++k) {
PdfObject obj = reader.getPdfObject(k);
if (obj != null) {
addToBody(obj, getNewObjectNumber(reader, k, 0));
}
}
}
else {
for (int k = 1; k < reader.getXrefSize(); ++k) {
PdfObject obj = reader.getPdfObjectRelease(k);
if (obj != null && skip != k) {
addToBody(obj, getNewObjectNumber(reader, k, 0), k != rootN);
}
}
}
}
finally {
try {
file.close();
}
catch (Exception e) {
// empty on purpose
}
}
PdfIndirectReference encryption = null;
PdfObject fileID = null;
if (crypto != null) {
if (append) {
encryption = reader.getCryptoRef();
}
else {
PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false);
encryption = encryptionObject.getIndirectReference();
}
fileID = crypto.getFileID();
}
PRIndirectReference iRoot = (PRIndirectReference)reader.trailer.get(PdfName.ROOT);
PdfIndirectReference root = new PdfIndirectReference(0, getNewObjectNumber(reader, iRoot.getNumber(), 0));
PdfIndirectReference info = null;
PdfDictionary oldInfo = (PdfDictionary)PdfReader.getPdfObject(iInfo);
PdfDictionary newInfo = new PdfDictionary();
if (oldInfo != null) {
for (Iterator i = oldInfo.getKeys().iterator(); i.hasNext();) {
PdfName key = (PdfName)i.next();
PdfObject value = PdfReader.getPdfObject(oldInfo.get(key));
newInfo.put(key, value);
}
}
if (moreInfo != null) {
for (Iterator i = moreInfo.keySet().iterator(); i.hasNext();) {
String key = (String)i.next();
PdfName keyName = new PdfName(key);
String value = (String)moreInfo.get(key);
if (value == null)
newInfo.remove(keyName);
else
newInfo.put(keyName, new PdfString(value, PdfObject.TEXT_UNICODE));
}
}
if (append) {
if (iInfo == null)
info = addToBody(newInfo, false).getIndirectReference();
else
info = addToBody(newInfo, iInfo.getNumber(), false).getIndirectReference();
}
else {
if (!newInfo.getKeys().isEmpty())
info = addToBody(newInfo, false).getIndirectReference();
}
// write the cross-reference table of the body
body.writeCrossReferenceTable(os, root, info, encryption, fileID, prevxref);
if (fullCompression) {
os.write(getISOBytes("startxref\n"));
os.write(getISOBytes(String.valueOf(body.offset())));
os.write(getISOBytes("\n%%EOF\n"));
}
else {
PdfTrailer trailer = new PdfTrailer(body.size(),
body.offset(),
root,
info,
encryption,
fileID, prevxref);
trailer.toPdf(this, os);
}
os.flush();
if (isCloseStream())
os.close();
reader.close();
}
void applyRotation(PdfDictionary pageN, ByteBuffer out) {
if (!rotateContents)
return;
Rectangle page = reader.getPageSizeWithRotation(pageN);
int rotation = page.getRotation();
switch (rotation) {
case 90:
out.append(PdfContents.ROTATE90);
out.append(page.top());
out.append(' ').append('0').append(PdfContents.ROTATEFINAL);
break;
case 180:
out.append(PdfContents.ROTATE180);
out.append(page.right());
out.append(' ');
out.append(page.top());
out.append(PdfContents.ROTATEFINAL);
break;
case 270:
out.append(PdfContents.ROTATE270);
out.append('0').append(' ');
out.append(page.right());
out.append(PdfContents.ROTATEFINAL);
break;
}
}
void alterContents() throws IOException {
for (Iterator i = pagesToContent.values().iterator(); i.hasNext();) {
PageStamp ps = (PageStamp)i.next();
PdfDictionary pageN = ps.pageN;
markUsed(pageN);
PdfArray ar = null;
PdfObject content = PdfReader.getPdfObject(pageN.get(PdfName.CONTENTS), pageN);
if (content == null) {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
}
else if (content.isArray()) {
ar = (PdfArray)content;
markUsed(ar);
}
else if (content.isStream()) {
ar = new PdfArray();
ar.add(pageN.get(PdfName.CONTENTS));
pageN.put(PdfName.CONTENTS, ar);
}
else {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
}
ByteBuffer out = new ByteBuffer();
if (ps.under != null) {
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(ps.under.getInternalBuffer());
out.append(PdfContents.RESTORESTATE);
}
if (ps.over != null)
out.append(PdfContents.SAVESTATE);
PdfStream stream = new PdfStream(out.toByteArray());
try{stream.flateCompress();}catch(Exception e){throw new ExceptionConverter(e);}
ar.addFirst(addToBody(stream).getIndirectReference());
out.reset();
if (ps.over != null) {
out.append(' ');
out.append(PdfContents.RESTORESTATE);
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(ps.over.getInternalBuffer());
out.append(PdfContents.RESTORESTATE);
stream = new PdfStream(out.toByteArray());
try{stream.flateCompress();}catch(Exception e){throw new ExceptionConverter(e);}
ar.add(addToBody(stream).getIndirectReference());
}
alterResources(ps);
}
}
void alterResources(PageStamp ps) {
ps.pageN.put(PdfName.RESOURCES, ps.pageResources.getResources());
}
protected int getNewObjectNumber(PdfReader reader, int number, int generation) {
IntHashtable ref = (IntHashtable)readers2intrefs.get(reader);
if (ref != null) {
int n = ref.get(number);
if (n == 0) {
n = getIndirectReferenceNumber();
ref.put(number, n);
}
return n;
}
if (currentPdfReaderInstance == null) {
if (append && number < initialXrefSize)
return number;
int n = myXref.get(number);
if (n == 0) {
n = getIndirectReferenceNumber();
myXref.put(number, n);
}
return n;
}
else
return currentPdfReaderInstance.getNewObjectNumber(number, generation);
}
RandomAccessFileOrArray getReaderFile(PdfReader reader) {
if (readers2intrefs.containsKey(reader)) {
RandomAccessFileOrArray raf = (RandomAccessFileOrArray)readers2file.get(reader);
if (raf != null)
return raf;
return reader.getSafeFile();
}
if (currentPdfReaderInstance == null)
return file;
else
return currentPdfReaderInstance.getReaderFile();
}
/**
* @param reader
* @param openFile
* @throws IOException
*/
public void registerReader(PdfReader reader, boolean openFile) throws IOException {
if (readers2intrefs.containsKey(reader))
return;
readers2intrefs.put(reader, new IntHashtable());
if (openFile) {
RandomAccessFileOrArray raf = reader.getSafeFile();
readers2file.put(reader, raf);
raf.reOpen();
}
}
/**
* @param reader
*/
public void unRegisterReader(PdfReader reader) {
if (!readers2intrefs.containsKey(reader))
return;
readers2intrefs.remove(reader);
RandomAccessFileOrArray raf = (RandomAccessFileOrArray)readers2file.get(reader);
if (raf == null)
return;
readers2file.remove(reader);
try{raf.close();}catch(Exception e){}
}
static void findAllObjects(PdfReader reader, PdfObject obj, IntHashtable hits) {
if (obj == null)
return;
switch (obj.type()) {
case PdfObject.INDIRECT:
PRIndirectReference iref = (PRIndirectReference)obj;
if (reader != iref.getReader())
return;
if (hits.containsKey(iref.getNumber()))
return;
hits.put(iref.getNumber(), 1);
findAllObjects(reader, PdfReader.getPdfObject(obj), hits);
return;
case PdfObject.ARRAY:
ArrayList lst = ((PdfArray)obj).getArrayList();
for (int k = 0; k < lst.size(); ++k) {
findAllObjects(reader, (PdfObject)lst.get(k), hits);
}
return;
case PdfObject.DICTIONARY:
case PdfObject.STREAM:
PdfDictionary dic = (PdfDictionary)obj;
for (Iterator it = dic.getKeys().iterator(); it.hasNext();) {
PdfName name = (PdfName)it.next();
findAllObjects(reader, dic.get(name), hits);
}
return;
}
}
/**
* @param fdf
* @throws IOException
*/
public void addComments(FdfReader fdf) throws IOException{
if (readers2intrefs.containsKey(fdf))
return;
PdfDictionary catalog = fdf.getCatalog();
catalog = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.FDF));
if (catalog == null)
return;
PdfArray annots = (PdfArray)PdfReader.getPdfObject(catalog.get(PdfName.ANNOTS));
if (annots == null || annots.size() == 0)
return;
registerReader(fdf, false);
IntHashtable hits = new IntHashtable();
HashMap irt = new HashMap();
ArrayList an = new ArrayList();
ArrayList ar = annots.getArrayList();
for (int k = 0; k < ar.size(); ++k) {
PdfObject obj = (PdfObject)ar.get(k);
PdfDictionary annot = (PdfDictionary)PdfReader.getPdfObject(obj);
PdfNumber page = (PdfNumber)PdfReader.getPdfObject(annot.get(PdfName.PAGE));
if (page == null || page.intValue() >= reader.getNumberOfPages())
continue;
findAllObjects(fdf, obj, hits);
an.add(obj);
if (obj.type() == PdfObject.INDIRECT) {
PdfObject nm = PdfReader.getPdfObject(annot.get(PdfName.NM));
if (nm != null && nm.type() == PdfObject.STRING)
irt.put(nm.toString(), obj);
}
}
int arhits[] = hits.getKeys();
for (int k = 0; k < arhits.length; ++k) {
int n = arhits[k];
PdfObject obj = fdf.getPdfObject(n);
if (obj.type() == PdfObject.DICTIONARY) {
PdfObject str = PdfReader.getPdfObject(((PdfDictionary)obj).get(PdfName.IRT));
if (str != null && str.type() == PdfObject.STRING) {
PdfObject i = (PdfObject)irt.get(str.toString());
if (i != null) {
PdfDictionary dic2 = new PdfDictionary();
dic2.merge((PdfDictionary)obj);
dic2.put(PdfName.IRT, i);
obj = dic2;
}
}
}
addToBody(obj, getNewObjectNumber(fdf, n, 0));
}
for (int k = 0; k < an.size(); ++k) {
PdfObject obj = (PdfObject)an.get(k);
PdfDictionary annot = (PdfDictionary)PdfReader.getPdfObject(obj);
PdfNumber page = (PdfNumber)PdfReader.getPdfObject(annot.get(PdfName.PAGE));
PdfDictionary dic = reader.getPageN(page.intValue() + 1);
PdfArray annotsp = (PdfArray)PdfReader.getPdfObject(dic.get(PdfName.ANNOTS), dic);
if (annotsp == null) {
annotsp = new PdfArray();
dic.put(PdfName.ANNOTS, annotsp);
markUsed(dic);
}
markUsed(annotsp);
annotsp.add(obj);
}
}
PageStamp getPageStamp(int pageNum) {
PdfDictionary pageN = reader.getPageN(pageNum);
PageStamp ps = (PageStamp)pagesToContent.get(pageN);
if (ps == null) {
ps = new PageStamp(this, reader, pageN);
pagesToContent.put(pageN, ps);
}
return ps;
}
PdfContentByte getUnderContent(int pageNum) {
if (pageNum < 1 || pageNum > reader.getNumberOfPages())
return null;
PageStamp ps = getPageStamp(pageNum);
if (ps.under == null)
ps.under = new StampContent(this, ps);
return ps.under;
}
PdfContentByte getOverContent(int pageNum) {
if (pageNum < 1 || pageNum > reader.getNumberOfPages())
return null;
PageStamp ps = getPageStamp(pageNum);
if (ps.over == null)
ps.over = new StampContent(this, ps);
return ps.over;
}
void correctAcroFieldPages(int page) {
if (acroFields == null)
return;
if (page > reader.getNumberOfPages())
return;
HashMap fields = acroFields.getFields();
for (Iterator it = fields.values().iterator(); it.hasNext();) {
AcroFields.Item item = (AcroFields.Item)it.next();
ArrayList pages = item.page;
for (int k = 0; k < pages.size(); ++k) {
int p = ((Integer)pages.get(k)).intValue();
if (p >= page)
pages.set(k, new Integer(p + 1));
}
}
}
void insertPage(int pageNumber, Rectangle mediabox) {
Rectangle media = new Rectangle(mediabox);
int rotation = media.getRotation() % 360;
PdfDictionary page = new PdfDictionary(PdfName.PAGE);
PdfDictionary resources = new PdfDictionary();
PdfArray procset = new PdfArray();
procset.add(PdfName.PDF);
procset.add(PdfName.TEXT);
procset.add(PdfName.IMAGEB);
procset.add(PdfName.IMAGEC);
procset.add(PdfName.IMAGEI);
resources.put(PdfName.PROCSET, procset);
page.put(PdfName.RESOURCES, resources);
page.put(PdfName.ROTATE, new PdfNumber(rotation));
page.put(PdfName.MEDIABOX, new PdfRectangle(media, rotation));
PRIndirectReference pref = reader.addPdfObject(page);
PdfDictionary parent;
PRIndirectReference parentRef;
if (pageNumber > reader.getNumberOfPages()) {
PdfDictionary lastPage = reader.getPageNRelease(reader.getNumberOfPages());
parentRef = (PRIndirectReference)lastPage.get(PdfName.PARENT);
parentRef = new PRIndirectReference(reader, parentRef.getNumber());
parent = (PdfDictionary)PdfReader.getPdfObject(parentRef);
PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent);
kids.add(pref);
markUsed(kids);
reader.pageRefs.insertPage(pageNumber, pref);
}
else {
if (pageNumber < 1)
pageNumber = 1;
PdfDictionary firstPage = reader.getPageN(pageNumber);
PRIndirectReference firstPageRef = reader.getPageOrigRef(pageNumber);
reader.releasePage(pageNumber);
parentRef = (PRIndirectReference)firstPage.get(PdfName.PARENT);
parentRef = new PRIndirectReference(reader, parentRef.getNumber());
parent = (PdfDictionary)PdfReader.getPdfObject(parentRef);
PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent);
ArrayList ar = kids.getArrayList();
int len = ar.size();
int num = firstPageRef.getNumber();
for (int k = 0; k < len; ++k) {
PRIndirectReference cur = (PRIndirectReference)ar.get(k);
if (num == cur.getNumber()) {
ar.add(k, pref);
break;
}
}
if (len == ar.size())
throw new RuntimeException("Internal inconsistence.");
markUsed(kids);
reader.pageRefs.insertPage(pageNumber, pref);
correctAcroFieldPages(pageNumber);
}
page.put(PdfName.PARENT, parentRef);
while (parent != null) {
markUsed(parent);
PdfNumber count = (PdfNumber)PdfReader.getPdfObjectRelease(parent.get(PdfName.COUNT));
parent.put(PdfName.COUNT, new PdfNumber(count.intValue() + 1));
parent = (PdfDictionary)PdfReader.getPdfObject(parent.get(PdfName.PARENT));
}
}
/** Getter for property rotateContents.
* @return Value of property rotateContents.
*
*/
boolean isRotateContents() {
return this.rotateContents;
}
/** Setter for property rotateContents.
* @param rotateContents New value of property rotateContents.
*
*/
void setRotateContents(boolean rotateContents) {
this.rotateContents = rotateContents;
}
boolean isContentWritten() {
return body.size() > 1;
}
AcroFields getAcroFields() {
if (acroFields == null) {
acroFields = new AcroFields(reader, this);
}
return acroFields;
}
void setFormFlattening(boolean flat) {
this.flat = flat;
}
void setFreeTextFlattening(boolean flat) {
this.flatFreeText = flat;
}
boolean partialFormFlattening(String name) {
getAcroFields();
if (acroFields.getXfa().isXfaPresent())
throw new UnsupportedOperationException("Partial form flattening is not supported with XFA forms.");
if (!acroFields.getFields().containsKey(name))
return false;
partialFlattening.add(name);
return true;
}
void flatFields() {
if (append)
throw new IllegalArgumentException("Field flattening is not supported in append mode.");
getAcroFields();
HashMap fields = acroFields.getFields();
if (fieldsAdded && partialFlattening.isEmpty()) {
for (Iterator i = fields.keySet().iterator(); i.hasNext();) {
partialFlattening.add(i.next());
}
}
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(reader.getCatalog().get(PdfName.ACROFORM));
ArrayList acroFds = null;
if (acroForm != null) {
PdfArray array = (PdfArray)PdfReader.getPdfObject(acroForm.get(PdfName.FIELDS), acroForm);
if (array != null)
acroFds = array.getArrayList();
}
for (Iterator i = fields.keySet().iterator(); i.hasNext();) {
String name = (String)i.next();
if (!partialFlattening.isEmpty() && !partialFlattening.contains(name))
continue;
AcroFields.Item item = (AcroFields.Item)fields.get(name);
for (int k = 0; k < item.merged.size(); ++k) {
PdfDictionary merged = (PdfDictionary)item.merged.get(k);
PdfNumber ff = (PdfNumber)PdfReader.getPdfObject(merged.get(PdfName.F));
int flags = 0;
if (ff != null)
flags = ff.intValue();
int page = ((Integer)item.page.get(k)).intValue();
PdfDictionary appDic = (PdfDictionary)PdfReader.getPdfObject(merged.get(PdfName.AP));
if (appDic != null && (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0) {
PdfObject obj = appDic.get(PdfName.N);
PdfAppearance app = null;
if (obj != null) {
PdfObject objReal = PdfReader.getPdfObject(obj);
if (obj instanceof PdfIndirectReference && !obj.isIndirect())
app = new PdfAppearance((PdfIndirectReference)obj);
else if (objReal instanceof PdfStream) {
((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM);
app = new PdfAppearance((PdfIndirectReference)obj);
}
else {
if (objReal.isDictionary()) {
PdfName as = (PdfName)PdfReader.getPdfObject(merged.get(PdfName.AS));
if (as != null) {
PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as);
if (iref != null) {
app = new PdfAppearance(iref);
if (iref.isIndirect()) {
objReal = PdfReader.getPdfObject(iref);
((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM);
}
}
}
}
}
}
if (app != null) {
Rectangle box = PdfReader.getNormalizedRectangle((PdfArray)PdfReader.getPdfObject(merged.get(PdfName.RECT)));
PdfContentByte cb = getOverContent(page);
cb.setLiteral("Q ");
cb.addTemplate(app, box.left(), box.bottom());
cb.setLiteral("q ");
}
}
if (partialFlattening.isEmpty())
continue;
PdfDictionary pageDic = reader.getPageN(page);
PdfArray annots = (PdfArray)PdfReader.getPdfObject(pageDic.get(PdfName.ANNOTS));
if (annots == null)
continue;
ArrayList ar = annots.getArrayList();
for (int idx = 0; idx < ar.size(); ++idx) {
PdfObject ran = (PdfObject)ar.get(idx);
if (!ran.isIndirect())
continue;
PdfObject ran2 = (PdfObject)item.widget_refs.get(k);
if (!ran2.isIndirect())
continue;
if (((PRIndirectReference)ran).getNumber() == ((PRIndirectReference)ran2).getNumber()) {
ar.remove(idx--);
PRIndirectReference wdref = (PRIndirectReference)ran2;
while (true) {
PdfDictionary wd = (PdfDictionary)PdfReader.getPdfObject(wdref);
PRIndirectReference parentRef = (PRIndirectReference)wd.get(PdfName.PARENT);
PdfReader.killIndirect(wdref);
if (parentRef == null) { // reached AcroForm
for (int fr = 0; fr < acroFds.size(); ++fr) {
PdfObject h = (PdfObject)acroFds.get(fr);
if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) {
acroFds.remove(fr);
--fr;
}
}
break;
}
PdfDictionary parent = (PdfDictionary)PdfReader.getPdfObject(parentRef);
PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS));
ArrayList kar = kids.getArrayList();
for (int fr = 0; fr < kar.size(); ++fr) {
PdfObject h = (PdfObject)kar.get(fr);
if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) {
kar.remove(fr);
--fr;
}
}
if (!kar.isEmpty())
break;
wdref = parentRef;
}
}
}
if (ar.size() == 0) {
PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS));
pageDic.remove(PdfName.ANNOTS);
}
}
}
if (!fieldsAdded && partialFlattening.isEmpty()) {
for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
PdfDictionary pageDic = reader.getPageN(page);
PdfArray annots = (PdfArray)PdfReader.getPdfObject(pageDic.get(PdfName.ANNOTS));
if (annots == null)
continue;
ArrayList ar = annots.getArrayList();
for (int idx = 0; idx < ar.size(); ++idx) {
PdfObject annoto = PdfReader.getPdfObject((PdfObject)ar.get(idx));
if ((annoto instanceof PdfIndirectReference) && !annoto.isIndirect())
continue;
PdfDictionary annot = (PdfDictionary)annoto;
if (PdfName.WIDGET.equals(annot.get(PdfName.SUBTYPE))) {
ar.remove(idx);
--idx;
}
}
if (ar.size() == 0) {
PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS));
pageDic.remove(PdfName.ANNOTS);
}
}
eliminateAcroformObjects();
}
}
void eliminateAcroformObjects() {
PdfObject acro = reader.getCatalog().get(PdfName.ACROFORM);
if (acro == null)
return;
PdfDictionary acrodic = (PdfDictionary)PdfReader.getPdfObject(acro);
reader.killXref(acrodic.get(PdfName.XFA));
acrodic.remove(PdfName.XFA);
PdfObject iFields = acrodic.get(PdfName.FIELDS);
if (iFields != null) {
PdfDictionary kids = new PdfDictionary();
kids.put(PdfName.KIDS, iFields);
sweepKids(kids);
PdfReader.killIndirect(iFields);
acrodic.put(PdfName.FIELDS, new PdfArray());
}
// PdfReader.killIndirect(acro);
// reader.getCatalog().remove(PdfName.ACROFORM);
}
void sweepKids(PdfObject obj) {
PdfObject oo = PdfReader.killIndirect(obj);
if (oo == null || !oo.isDictionary())
return;
PdfDictionary dic = (PdfDictionary)oo;
PdfArray kids = (PdfArray)PdfReader.killIndirect(dic.get(PdfName.KIDS));
if (kids == null)
return;
ArrayList ar = kids.getArrayList();
for (int k = 0; k < ar.size(); ++k) {
sweepKids((PdfObject)ar.get(k));
}
}
private void flatFreeTextFields()
{
if (append)
throw new IllegalArgumentException("FreeText flattening is not supported in append mode.");
for (int page = 1; page <= reader.getNumberOfPages(); ++page)
{
PdfDictionary pageDic = reader.getPageN(page);
PdfArray annots = (PdfArray)PdfReader.getPdfObject(pageDic.get(PdfName.ANNOTS));
if (annots == null)
continue;
ArrayList ar = annots.getArrayList();
for (int idx = 0; idx < ar.size(); ++idx)
{
PdfObject annoto = PdfReader.getPdfObject((PdfObject)ar.get(idx));
if ((annoto instanceof PdfIndirectReference) && !annoto.isIndirect())
continue;
PdfDictionary annDic = (PdfDictionary)annoto;
if (!((PdfName)annDic.get(PdfName.SUBTYPE)).equals(PdfName.FREETEXT))
continue;
PdfNumber ff = (PdfNumber)PdfReader.getPdfObject(annDic.get(PdfName.F));
int flags = (ff != null) ? ff.intValue() : 0;
if ( (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0)
{
PdfObject obj1 = annDic.get(PdfName.AP);
if (obj1 == null)
continue;
PdfDictionary appDic = (obj1 instanceof PdfIndirectReference) ?
(PdfDictionary) PdfReader.getPdfObject(obj1) : (PdfDictionary) obj1;
PdfObject obj = appDic.get(PdfName.N);
PdfAppearance app = null;
PdfObject objReal = PdfReader.getPdfObject(obj);
if (obj instanceof PdfIndirectReference && !obj.isIndirect())
app = new PdfAppearance((PdfIndirectReference)obj);
else if (objReal instanceof PdfStream)
{
((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM);
app = new PdfAppearance((PdfIndirectReference)obj);
}
else
{
if (objReal.isDictionary())
{
PdfName as_p = (PdfName)PdfReader.getPdfObject(appDic.get(PdfName.AS));
if (as_p != null)
{
PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as_p);
if (iref != null)
{
app = new PdfAppearance(iref);
if (iref.isIndirect())
{
objReal = PdfReader.getPdfObject(iref);
((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM);
}
}
}
}
}
if (app != null)
{
Rectangle box = PdfReader.getNormalizedRectangle((PdfArray)PdfReader.getPdfObject(annDic.get(PdfName.RECT)));
PdfContentByte cb = getOverContent(page);
cb.setLiteral("Q ");
cb.addTemplate(app, box.left(), box.bottom());
cb.setLiteral("q ");
}
}
if (partialFlattening.size() == 0)
continue;
}
for (int idx = 0; idx < ar.size(); ++idx)
{
PdfObject annoto = PdfReader.getPdfObject((PdfObject)ar.get(idx));
if ((annoto instanceof PdfIndirectReference) && annoto.isIndirect())
{
PdfDictionary annot = (PdfDictionary)annoto;
if (PdfName.FREETEXT.equals(annot.get(PdfName.SUBTYPE)))
{
ar.remove(idx);
--idx;
}
}
}
if (ar.size() == 0)
{
PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS));
pageDic.remove(PdfName.ANNOTS);
}
}
}
/**
* @see com.lowagie.text.pdf.PdfWriter#getPageReference(int)
*/
public PdfIndirectReference getPageReference(int page) {
PdfIndirectReference ref = reader.getPageOrigRef(page);
if (ref == null)
throw new IllegalArgumentException("Invalid page number " + page);
return ref;
}
/**
* @see com.lowagie.text.pdf.PdfWriter#addAnnotation(com.lowagie.text.pdf.PdfAnnotation)
*/
public void addAnnotation(PdfAnnotation annot) {
throw new RuntimeException("Unsupported in this context. Use PdfStamper.addAnnotation()");
}
void addDocumentField(PdfIndirectReference ref) {
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog);
if (acroForm == null) {
acroForm = new PdfDictionary();
catalog.put(PdfName.ACROFORM, acroForm);
markUsed(catalog);
}
PdfArray fields = (PdfArray)PdfReader.getPdfObject(acroForm.get(PdfName.FIELDS), acroForm);
if (fields == null) {
fields = new PdfArray();
acroForm.put(PdfName.FIELDS, fields);
markUsed(acroForm);
}
fields.add(ref);
markUsed(fields);
}
void addFieldResources() {
if (fieldTemplates.size() == 0)
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog);
if (acroForm == null) {
acroForm = new PdfDictionary();
catalog.put(PdfName.ACROFORM, acroForm);
markUsed(catalog);
}
PdfDictionary dr = (PdfDictionary)PdfReader.getPdfObject(acroForm.get(PdfName.DR), acroForm);
if (dr == null) {
dr = new PdfDictionary();
acroForm.put(PdfName.DR, dr);
markUsed(acroForm);
}
markUsed(dr);
for (Iterator it = fieldTemplates.keySet().iterator(); it.hasNext();) {
PdfTemplate template = (PdfTemplate)it.next();
PdfFormField.mergeResources(dr, (PdfDictionary)template.getResources(), this);
}
PdfDictionary fonts = (PdfDictionary)PdfReader.getPdfObject(dr.get(PdfName.FONT));
if (fonts != null && acroForm.get(PdfName.DA) == null) {
acroForm.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
markUsed(acroForm);
}
}
void expandFields(PdfFormField field, ArrayList allAnnots) {
allAnnots.add(field);
ArrayList kids = field.getKids();
if (kids != null) {
for (int k = 0; k < kids.size(); ++k)
expandFields((PdfFormField)kids.get(k), allAnnots);
}
}
void addAnnotation(PdfAnnotation annot, PdfDictionary pageN) {
try {
ArrayList allAnnots = new ArrayList();
if (annot.isForm()) {
fieldsAdded = true;
getAcroFields();
PdfFormField field = (PdfFormField)annot;
if (field.getParent() != null)
return;
expandFields(field, allAnnots);
}
else
allAnnots.add(annot);
for (int k = 0; k < allAnnots.size(); ++k) {
annot = (PdfAnnotation)allAnnots.get(k);
if (annot.getPlaceInPage() > 0)
pageN = reader.getPageN(annot.getPlaceInPage());
if (annot.isForm()) {
if (!annot.isUsed()) {
HashMap templates = annot.getTemplates();
if (templates != null)
fieldTemplates.putAll(templates);
}
PdfFormField field = (PdfFormField)annot;
if (field.getParent() == null)
addDocumentField(field.getIndirectReference());
}
if (annot.isAnnotation()) {
PdfArray annots = (PdfArray)PdfReader.getPdfObject(pageN.get(PdfName.ANNOTS), pageN);
if (annots == null) {
annots = new PdfArray();
pageN.put(PdfName.ANNOTS, annots);
markUsed(pageN);
}
annots.add(annot.getIndirectReference());
markUsed(annots);
if (!annot.isUsed()) {
PdfRectangle rect = (PdfRectangle)annot.get(PdfName.RECT);
if (rect != null && (rect.left() != 0 || rect.right() != 0 || rect.top() != 0 || rect.bottom() != 0)) {
int rotation = reader.getPageRotation(pageN);
Rectangle pageSize = reader.getPageSizeWithRotation(pageN);
switch (rotation) {
case 90:
annot.put(PdfName.RECT, new PdfRectangle(
pageSize.top() - rect.bottom(),
rect.left(),
pageSize.top() - rect.top(),
rect.right()));
break;
case 180:
annot.put(PdfName.RECT, new PdfRectangle(
pageSize.right() - rect.left(),
pageSize.top() - rect.bottom(),
pageSize.right() - rect.right(),
pageSize.top() - rect.top()));
break;
case 270:
annot.put(PdfName.RECT, new PdfRectangle(
rect.bottom(),
pageSize.right() - rect.left(),
rect.top(),
pageSize.right() - rect.right()));
break;
}
}
}
}
if (!annot.isUsed()) {
annot.setUsed();
addToBody(annot, annot.getIndirectReference());
}
}
}
catch (IOException e) {
throw new ExceptionConverter(e);
}
}
void addAnnotation(PdfAnnotation annot, int page) {
addAnnotation(annot, reader.getPageN(page));
}
private void outlineTravel(PRIndirectReference outline) {
while (outline != null) {
PdfDictionary outlineR = (PdfDictionary)PdfReader.getPdfObjectRelease(outline);
PRIndirectReference first = (PRIndirectReference)outlineR.get(PdfName.FIRST);
if (first != null) {
outlineTravel(first);
}
PdfReader.killIndirect(outlineR.get(PdfName.DEST));
PdfReader.killIndirect(outlineR.get(PdfName.A));
PdfReader.killIndirect(outline);
outline = (PRIndirectReference)outlineR.get(PdfName.NEXT);
}
}
void deleteOutlines() {
PdfDictionary catalog = reader.getCatalog();
PRIndirectReference outlines = (PRIndirectReference)catalog.get(PdfName.OUTLINES);
if (outlines == null)
return;
outlineTravel(outlines);
PdfReader.killIndirect(outlines);
catalog.remove(PdfName.OUTLINES);
markUsed(catalog);
}
void setJavaScript() throws IOException {
ArrayList djs = pdf.getDocumentJavaScript();
if (djs.size() == 0)
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES), catalog);
if (names == null) {
names = new PdfDictionary();
catalog.put(PdfName.NAMES, names);
markUsed(catalog);
}
markUsed(names);
String s = String.valueOf(djs.size() - 1);
int n = s.length();
String pad = "000000000000000";
HashMap maptree = new HashMap();
for (int k = 0; k < djs.size(); ++k) {
s = String.valueOf(k);
s = pad.substring(0, n - s.length()) + s;
maptree.put(s, djs.get(k));
}
PdfDictionary tree = PdfNameTree.writeTree(maptree, this);
names.put(PdfName.JAVASCRIPT, addToBody(tree).getIndirectReference());
}
void addFileAttachments() throws IOException {
HashMap fs = pdf.getDocumentFileAttachment();
if (fs.size() == 0)
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES), catalog);
if (names == null) {
names = new PdfDictionary();
catalog.put(PdfName.NAMES, names);
markUsed(catalog);
}
markUsed(names);
HashMap old = PdfNameTree.readTree((PdfDictionary)PdfReader.getPdfObjectRelease(names.get(PdfName.EMBEDDEDFILES)));
for (Iterator it = fs.keySet().iterator(); it.hasNext();) {
String name = (String)it.next();
int k = 0;
String nn = name;
while (old.containsKey(nn)) {
++k;
nn += " " + k;
}
old.put(nn, fs.get(name));
}
PdfDictionary tree = PdfNameTree.writeTree(old, this);
names.put(PdfName.EMBEDDEDFILES, addToBody(tree).getIndirectReference());
}
void setOutlines() throws IOException {
if (newBookmarks == null)
return;
deleteOutlines();
if (newBookmarks.size() == 0)
return;
namedAsNames = (reader.getCatalog().get(PdfName.DESTS) != null);
PdfDictionary top = new PdfDictionary();
PdfIndirectReference topRef = getPdfIndirectReference();
Object kids[] = SimpleBookmark.iterateOutlines(this, topRef, newBookmarks, namedAsNames);
top.put(PdfName.FIRST, (PdfIndirectReference)kids[0]);
top.put(PdfName.LAST, (PdfIndirectReference)kids[1]);
top.put(PdfName.COUNT, new PdfNumber(((Integer)kids[2]).intValue()));
addToBody(top, topRef);
reader.getCatalog().put(PdfName.OUTLINES, topRef);
markUsed(reader.getCatalog());
}
void setOutlines(List outlines) {
newBookmarks = outlines;
}
/**
* Sets the viewer preferences.
* @param preferences the viewer preferences
* @see PdfWriter#setViewerPreferences(int)
*/
public void setViewerPreferences(int preferences) {
useVp = true;
vp |= preferences;
}
/**
* Set the signature flags.
* @param f the flags. This flags are ORed with current ones
*/
public void setSigFlags(int f) {
sigFlags |= f;
}
/** Always throws an <code>UnsupportedOperationException</code>.
* @param actionType ignore
* @param action ignore
* @throws PdfException ignore
* @see PdfStamper#setPageAction(PdfName, PdfAction, int)
*/
public void setPageAction(PdfName actionType, PdfAction action) throws PdfException {
throw new UnsupportedOperationException("Use setPageAction(PdfName actionType, PdfAction action, int page)");
}
/**
* Sets the open and close page additional action.
* @param actionType the action type. It can be <CODE>PdfWriter.PAGE_OPEN</CODE>
* or <CODE>PdfWriter.PAGE_CLOSE</CODE>
* @param action the action to perform
* @param page the page where the action will be applied. The first page is 1
* @throws PdfException if the action type is invalid
*/
void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException {
if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE))
throw new PdfException("Invalid page additional action type: " + actionType.toString());
PdfDictionary pg = reader.getPageN(page);
PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.AA), pg);
if (aa == null) {
aa = new PdfDictionary();
pg.put(PdfName.AA, aa);
markUsed(pg);
}
aa.put(actionType, action);
markUsed(aa);
}
/**
* Always throws an <code>UnsupportedOperationException</code>.
* @param seconds ignore
*/
public void setDuration(int seconds) {
throw new UnsupportedOperationException("Use setPageAction(PdfName actionType, PdfAction action, int page)");
}
/**
* Always throws an <code>UnsupportedOperationException</code>.
* @param transition ignore
*/
public void setTransition(PdfTransition transition) {
throw new UnsupportedOperationException("Use setPageAction(PdfName actionType, PdfAction action, int page)");
}
/**
* Sets the display duration for the page (for presentations)
* @param seconds the number of seconds to display the page. A negative value removes the entry
* @param page the page where the duration will be applied. The first page is 1
*/
void setDuration(int seconds, int page) {
PdfDictionary pg = reader.getPageN(page);
if (seconds < 0)
pg.remove(PdfName.DUR);
else
pg.put(PdfName.DUR, new PdfNumber(seconds));
markUsed(pg);
}
/**
* Sets the transition for the page
* @param transition the transition object. A <code>null</code> removes the transition
* @param page the page where the transition will be applied. The first page is 1
*/
void setTransition(PdfTransition transition, int page) {
PdfDictionary pg = reader.getPageN(page);
if (transition == null)
pg.remove(PdfName.TRANS);
else
pg.put(PdfName.TRANS, transition.getTransitionDictionary());
markUsed(pg);
}
protected void markUsed(PdfObject obj) {
if (append && obj != null) {
PRIndirectReference ref = null;
if (obj.type() == PdfObject.INDIRECT)
ref = (PRIndirectReference)obj;
else
ref = obj.getIndRef();
if (ref != null)
marked.put(ref.getNumber(), 1);
}
}
protected void markUsed(int num) {
if (append)
marked.put(num, 1);
}
/**
* Getter for property append.
* @return Value of property append.
*/
boolean isAppend() {
return append;
}
/** Additional-actions defining the actions to be taken in
* response to various trigger events affecting the document
* as a whole. The actions types allowed are: <CODE>DOCUMENT_CLOSE</CODE>,
* <CODE>WILL_SAVE</CODE>, <CODE>DID_SAVE</CODE>, <CODE>WILL_PRINT</CODE>
* and <CODE>DID_PRINT</CODE>.
*
* @param actionType the action type
* @param action the action to execute in response to the trigger
* @throws PdfException on invalid action type
*/
public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException {
if (!(actionType.equals(DOCUMENT_CLOSE) ||
actionType.equals(WILL_SAVE) ||
actionType.equals(DID_SAVE) ||
actionType.equals(WILL_PRINT) ||
actionType.equals(DID_PRINT))) {
throw new PdfException("Invalid additional action type: " + actionType.toString());
}
PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(reader.getCatalog().get(PdfName.AA));
if (aa == null) {
if (action == null)
return;
aa = new PdfDictionary();
reader.getCatalog().put(PdfName.AA, aa);
}
markUsed(aa);
if (action == null)
aa.remove(actionType);
else
aa.put(actionType, action);
}
/**
* @see com.lowagie.text.pdf.PdfWriter#setOpenAction(com.lowagie.text.pdf.PdfAction)
*/
public void setOpenAction(PdfAction action) {
openAction = action;
}
/**
* @see com.lowagie.text.pdf.PdfWriter#setOpenAction(java.lang.String)
*/
public void setOpenAction(String name) {
throw new UnsupportedOperationException("Open actions by name are not supported.");
}
/**
* @see com.lowagie.text.pdf.PdfWriter#setThumbnail(com.lowagie.text.Image)
*/
public void setThumbnail(com.lowagie.text.Image image) {
throw new UnsupportedOperationException("Use PdfStamper.setThumbnail().");
}
void setThumbnail(Image image, int page) throws PdfException, DocumentException {
PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image));
reader.resetReleasePage();
PdfDictionary dic = reader.getPageN(page);
dic.put(PdfName.THUMB, thumb);
reader.resetReleasePage();
}
public PdfContentByte getDirectContentUnder() {
throw new UnsupportedOperationException("Use PdfStamper.getUnderContent() or PdfStamper.getOverContent()");
}
public PdfContentByte getDirectContent() {
throw new UnsupportedOperationException("Use PdfStamper.getUnderContent() or PdfStamper.getOverContent()");
}
static class PageStamp {
PdfDictionary pageN;
StampContent under;
StampContent over;
PageResources pageResources;
PageStamp(PdfStamperImp stamper, PdfReader reader, PdfDictionary pageN) {
this.pageN = pageN;
pageResources = new PageResources();
PdfDictionary resources = (PdfDictionary)PdfReader.getPdfObject(pageN.get(PdfName.RESOURCES));
pageResources.setOriginalResources(resources, stamper.namePtr);
}
}
}
|