Try adding a bookmark to existing PDF using iText

I copied the code I put on cfsearching for the concatenation of PDF files and all existing bookmarks ( http://cfsearching.blogspot.com/2007/12/getting-started-with-itext-part-17.html ), bought the book of iTextinAction, but am stuck when you try to add a new bookmark. I get the message " "

java.util.ArrayList cannot be cast in java.util.HashMap.

I think I'm not add my own bookmarks "custom" to the list of existing bookmarks correctly. I tried to change the list of existing bookmarks for an explicit vector (that was how the example was written) in a table instead, but still have this problem when I try to close my document. Here is the code that I modified. I'd appreciate any help. I'm not a Java programmer and am really struggling to understand how it works and how to make changes.

<cfscript>
  savedErrorMessage = "";

  // cfSearching: All file paths are relative to the current directory
  fullPathToOutputFile = ExpandPath("./Concatenated.pdf");
  arrayOfInputFiles = arrayNew(1);
  arrayAppend(arrayOfInputFiles, ExpandPath("./Version control.pdf"));
  arrayAppend(arrayOfInputFiles, ExpandPath("./iTextinAction,SecondEdition.pdf"));
  try {

      pageOffset = 0;
      PdfReader = createObject("java", "com.lowagie.text.pdf.PdfReader");
      SimpleBookmark = createObject("java", "com.lowagie.text.pdf.SimpleBookmark");
      // cfSearching: Internally CF stores arrays as Vectors. So I chose to use an explict vector
      // cfSearching:  here, but you could use an array and CF array functions instead
      allBookmarks = createObject("java", "java.util.Vector");

       outlines = arrayNew(1);
     arrayAppend(outlines, 'Pirate Jack');

      for ( fileIndex = 1; fileIndex LTE arrayLen(arrayOfInputFiles); fileIndex = fileIndex + 1) {
          // we create a reader for a certain document
          reader = pdfReader.init( arrayOfInputFiles[fileIndex] );
          reader.consolidateNamedDestinations();
          // we retrieve the total number of pages
          totalPages = reader.getNumberOfPages();
          bookmarks = SimpleBookmark.getBookmark(reader);
          if (IsDefined("bookmarks")) {
              if (pageOffset neq 0) {
                  SimpleBookmark.shiftPageNumbers(bookmarks, javacast("int", pageOffset), javacast("null", 0));
              }
              allBookmarks.addAll(bookmarks);
          }

          pageOffset = pageOffset + totalPages;

          if (fileIndex EQ 1) {
              // step 1: creation of a document-object
              document = createObject("java", "com.lowagie.text.Document");
              document = document.init( reader.getPageSizeWithRotation( javacast("int", 1)) );
              // step 2: we create a writer that listens to the document
              outStream = createObject("java", "java.io.FileOutputStream").init( fullPathToOutputFile );
              pdfWriter = createObject("java", "com.lowagie.text.pdf.PdfCopy").init(document, outStream);
              // step 3: we open the document
              document.open();
           }
           // step 4: we add content
           for (pageIndex = 1; pageIndex LTE totalPages; pageIndex = pageIndex + 1) {
                page = pdfWriter.getImportedPage(reader, javacast("int", pageIndex) );
                pdfWriter.addPage(page);
           }

           formFields = reader.getAcroForm();
           if (IsDefined("formFields")) {
              pdfWriter.copyAcroForm(reader);
           }
      }
      if (arraylen(outlines) gt 0) {
          allBookmarks.addAll(outlines);
      }

      if (NOT allBookmarks.isEmpty()) {
          pdfWriter.setOutlines( allBookmarks );
      }

      // step 5: we close the document
      document.close();

      WriteOutput("Finished!");
  }
  catch (java.language.Exception de) {
      savedErrorMessage = de;
  }
  // cfSearching: close document and output stream objects
  if (IsDefined("document")) {
      document.close();
  }
  if (IsDefined("outputStream")) {
      outputStream.close();
  }
</cfscript>

This entry is old _really_ ;-)  CF8/9 introduced a bunch of new features which removed a lot of the need to plunge down into iText for basic pdf stuff.  For example

http://www.coldfusionjedi.com/index.cfm/2010/2/19/quick-tip-adding-a-bookmark-to-a-PDF-whe n-TI-a-none

contours = arrayNew (1);
arrayAppend (contours, 'Pirate Jack');

But... the bookmarks are more than simple text. This is the reason why the error occurs. Bookmarks are like a structure and can consist of properties, such as a title, action, url, number of pages, style etc. It is not as simple as adding a string. To see what a bookmark object looks like CF, empty variable "bookmarks" just after the isDefined():

....

If (IsDefined ("bookmarks")) {}

use WriteDump() for CF8 to CF9 try http://www.cflib.org/udf/Dump
dump (bookmarks);

....

}

-Leigh

Tags: ColdFusion

Similar Questions

  • Adding text to PDF using iText instead of CFPDF

    Hello

    I know this may seem a bit off-topic is posted here, but I ask this Council because I am a complete JAVA noob and I guess some of you folk CF could do that before.

    In any case, on my question... I'm already add a watermark image to a PDF using iText (CF8) with the help of colleagues poster (= cfSearching =).  I'm looking for is the best way to go about adding text to the same pdf.  I have to add 4 lines of text (with specific font and size) and Center it under the image being added.   Someone at - it a site they could tell me how to add text in the form and how do I get the width of this text to align properly?  I have search Google and watched a lot of JAVA code but be a noob JAVA, it's hard to know exactly what libs and methods you can use to do this.

    Any help would be greatly appreciated!

    -Michael

    The classes you need are PdfTable and PdfCell

    http://cfsearching.blogspot.com/2008/09/getting-started-with-iText-tables.html

    I was curious, I threw together a rough example. It adds the table in a pdfTemplate, then the model adds watermark to each page. The positioning and table dimensions are based on my sample data, so you'll need to tweak the.  Make sure that the dimensions of the model are large enough to accommodate your image and your text. If the dimensions are not large enough, the watermark is perhaps not visible.


    Err = "";
    TEST VALUES
    maxlinechars = 40;
    dCompany = "Google Inc.";
    dnom = "1600 Amphitheatre Parkway";
    dPhone = '+ 1 650-253-0000';
    dEmail = "[email protected]";
       
    simplify the code by putting the watermark text values in a table
    TextElement = [dCompany, dName, dPhone, dEmail];
    inputFile = ExpandPath ("ChapterSection.pdf");
    outputFile = ExpandPath ("ChapterSection_Watermark_ImageWithText.pdf");
    imgPath = ExpandPath("/dev/beveled_purpleblue.png");

    try {}
    initialize objects to read and write the pdf file
    pdfReader is createObject ("java", "com.lowagie.text.pdf.PdfReader") .init (inputFile);.
    outStream is createObject ("java", "java.io.FileOutputStream") .init (outputFile);.
    pdfStamper is createObject ("java", "com.lowagie.text.pdf.PdfStamper") .init (pdfReader, outStream);.

    get the size of the watermark image
    Note: table width and height are examples of values for demo only...
    Watch to your dimensions are large enough to accomdate your text and image
    otherwise the watermark is perhaps not entirely visible
    IMG is createObject ("java", "com.lowagie.text.Image") .getInstance (imgPath);.
    tableWidth = img.width () + 100;
    tableHeight = img.height () + 75;
           
    create a template for the table storage
    CB = pdfStamper.getOverContent (1);
    model = cb.createTemplate (tableHeight, tableWidth);

    create a single-column table
    table = createObject ("java", "com.lowagie.text.pdf.PdfPTable") .init (1);
    table.setTotalWidth (tableWidth);

    reusable objects for adding rows in the table
    PdfCell = createObject ("java", "com.lowagie.text.pdf.PdfPCell");
    Expression = createObject ("java", "com.lowagie.text.Phrase");

    Add the watermark image to the first line
    imageCell = PdfCell.init (img, false);
    imageCell.setBorder (PdfCell.NO_BORDER);
    imageCell.setHorizontalAlignment (PdfCell.ALIGN_CENTER);
    table.addCell (imageCell);

    Add each piece of text in the table of a new line
    for (x = 1; x<= arraylen(textelements);="" x++)="">
    textCell = PdfCell.init (Phrase.init (TextElement [x]));
    textCell.setBorder (PdfCell.NO_BORDER);
    textCell.setHorizontalAlignment (PdfCell.ALIGN_CENTER);
    table.addCell (textCell);
    }
           
    get the calculated height of table
    table.calculateHeightsFast ();
    tableHeight = table.getTotalHeight ();
    table.writeSelectedRows (0, - 1, 0, tableHeight, model);
    WriteOutput ("calculated tableWidth =" tableWidth & ", tableHeight =" "& tableHeight &")
    ");

    Add model watermark to each page
    Note: x / yPos values are for demo only (in upper right)...
    i = 0;
    totalPages = pdfReader.getNumberOfPages ();
    so that {(i LT totalPages)
    i = i + 1;
    content = pdfStamper.getOverContent (javacast ("int", i));
    positioning of arbitrary code
    pageSize = pdfReader.getPageSize (i);
    yPos = pageSize.height () - tableHeight - 15;
    PosX = (pageSize.width () - tableWidth)-25;
    content.addTemplate (template, xPos, yPos);
    WriteOutput ("watermarked page" & I & "xPos =" & xPos & ", yPos =" "& yPos &")
    ");
    }
    }
    catch (Exception e) {}
    ERR = e;
    }
    If (IsDefined ("pdfStamper")) {}
    pdfStamper.close ();
    }

    If (IsDefined ("outStream"))
    {
    outStream.close ();
    }

  • Adding Pages scanned in existing PDF files

    Hi all

    I'll try to find a way to add new pages to existing PDF file.

    Is it possible to scan new pages directly to the existing PDF file?

    According to the current help files, it shows in the following 2 ways:

    1. combine multiple files of multiple type after scanning and save the file to the local computer.

    2. let continue scanning when scanning additional pages.

    But how we can scan the new pages in existing file and the open PDF.

    Concerning

    Kirubaa

    You use what Version of Acrobat? For Acrobat 11.0.4 If you have a PDF document is opened and as you scan a document it will automatically add to the existing PDF. For other versions, you must go to custom scan and select "Add to the existing file or portfolio" whenever you want to add.

    Thank you

    Bad Boy

  • Generate PDF with itext in PL/SQL

    Hello

    I am generating some PL/SQL PDF using itext. I loaded iText - 5.0.4.jar, but found a few invalid javaclass, after going through a lot of forums I found some suggestion that I need to load a jar file more so I loaded the
    loadjava - < user > / < pw > bcmail-jdk14 - 147.jar
    loadjava - < user > / < pw > bcprov-jdk14 - 147.jar
    then again loaded iText - 5.0.4.jar, but the result is the same.
    I use oracle DB 11.2 on 64-bit Windows.
    I also tried with bcprov-jdk15on - 147.jar and bcmail-jdk15on - 147.jar
    because the version of java database is
    Java version "1.5.0_17.
    Java (TM) 2 Runtime Environment, Standard Edition (build 1.5.0_17 - b04)
    Java for 64-bit Server VM (build 1.5.0_17 - b04, mixed mode)

    need help to solve this problem. Please let me know if you need more information. Thnax

    I have tried with - genmissing - v - r but had the following problems.
    What authorization I give to load jar files also I want to drop the file jar to do a fresh charge, but dropjava gives file not found error.

    jump: com/itextpdf/text/pdf/hyphenation/CharVector of class
    resolution: com/itextpdf/text/pdf/standard/standard class
    error: com/itextpdf/text/pdf/standard/standard class
    ORA-29534: referenced object SAMPACC.com/itextpdf/text/pdf/BaseFont could not
    t be resolved
    resolution: com/itextpdf/text/pdf/hyphenation/HyphenationTree of class
    error: com/itextpdf/text/pdf/hyphenation/HyphenationTree of class
    ORA-29534: referenced object SAMPACC.com/itextpdf/text/pdf/hyphenation/Simpl
    ePatternParser could not be resolved
    jump: class com/itextpdf/text/pdf/hyphenation/TernaryTree$ iterator$ Item
    jump: class com/itextpdf/text/pdf/hyphenation/TernaryTree$ iterator

    Error creating java, security, interfaces, ECPublicKey class
    ORA-29545: Malformed class: user attempted to load a class (java.secu
    rity.interfaces.ECPublicKey) in a small set. The authorization may be part
    d using dbms_java.grant_permission (, LoadClassInPackage...
    ORA-06512: at line 1

    The following is not
    class java, security, interfaces, ECPublicKey: creation (failure)
    output: failure occurred during treatment

    Published by: pkpanda on January 9, 2013 18:01

  • Is it possible to create a PDF file using only the pages of an existing PDF?

    Is it possible to create a PDF file using only the pages of an existing PDF?

    Hi drdanger,

    There is a way, and it requires Acrobat. You need Acrobat to extract pages from a PDF. You are welcome to try free for 30 days, Acrobat, if you haven't already. See www.adobe.com/products/acrobat.html for more information.

    If Acrobat, you choose extract in the Pages of the Toolbox pane, then specify which pages you want to extract. These pages are extracted to a new PDF file, which then you name and save it.

    Best,

    Sara

  • How can I add white space between areas that contain text fields? I use Adobe Acrobat Pro DC 2015.  I'm trying to change an existing PDF. I need to add white space between areas that contain text fields to allow these text fields to be developed and not

    How can I add white space between areas that contain text fields?

    I use Adobe Acrobat Pro DC 2015.

    I'm trying to change an existing PDF. I need to add white space between areas that contain text fields to allow these areas to be developed and do not overlap the text and the text below fields.

    For example:

    1. 1.

    Progress/strategies:

    1. 2.

    Progress/strategies:

    1. 3.

    Progress/strategies:

    1. 4.

    Progress/strategies:

    The space between each 'progress/strategies' increasing needs. A text field is under each of them. If it's a Word doc, I could just press on enter. What is the best way to do this with Adobe Acrobat Pro DC?

    There is no easy way to do it. You need to move the text fields more apart and if there are static elements, then you will need to use the tool edit text & Images to move them, separately.

  • My Adobe Acrobat widget does not work. Whenever I try to convert a webpage to PDF, a window opens saying that "any version of Acrobat can be found, install Acrobat 11.0.09 or update version to use the extension create PDFs.» I downloaded the last drunk ve

    My Adobe Acrobat widget does not work. Whenever I try to convert a webpage to PDF, a window opens saying that "any version of Acrobat can be found, install Acrobat 11.0.09 or update version to use the extension create PDFs.» I downloaded the latest version but iut still does not work. I use a MAC and Chrome as a browser.

    Can you help me?

    If you use Adobe Reader, you will not be able to create a PDF file. Adobe Reader cannot create a PDF file, modify/edit the content of a PDF page or export the contents of a PDF page.

    For those, you must use Acrobat or one of Adobe's online subscription services.

    Be well...

  • Can I resize a PDF using adobe readerX existing file?

    Can I resize an existing PDF file with adobe reader X?

    No, the free player has no editing capabilities. You need a program such as Acrobat.

  • Add to an existing PDF... Do NOT combine...

    We have just installed Adobe DC on all our computers.  We have already created PDF docs it takes often add scanned a new page or two that work is progressing on a project.  All previous Acrobat programs allowed us to add an analysis of the existing. It seems that we can only "combine" with DC?  Too many steps to create a new scan with one or two pages, mix, then he must go back and remove the new scan.  Help!

    Hello

    Please, try the following:

    Open the PDF in Acrobat ms

    Go to file > create > PDF from Scanner > Custom Scan

    Select it your entry as sides, color Mode, scan, options etc.

    In the output pane, add to the existing file or portfolio must be selected for the PDF which is open

    Now scan the document in PDF format, it will be added to the currently open PDF format

    Thank you

    Abhishek

  • What product Adobe do I need to add page numbers to an existing PDF?

    What product Adobe do I need to add page numbers to an existing PDF?

    I agree with Adobe PDF Pack.  This provides me with what I need?

    Hi questioner_00001,

    To edit a PDF file, such as adding page numbers, you need Acrobat. PDF Pack does not offer this feature. You can try Acrobat free for 30 days if you wish. For more information, see www.adobe.com/products/acrobat.html.

    Best,

    Sara

  • How can I insert another PDF file into an existing PDF page

    Here is some information.  I used to use Acrobat 5 (I know it's really old, but it worked fine for my needs, but it's time to upgrade).  I have a document PDF 1 page that exists (for example, an invoice).  Sometimes in Excel I create additional supporting details/calculations/etc that I have to place on the Bill.  In the past I would print my Excel document to PDF using PDF Broadgun (great tool!) - and I would like to continue to do that.  Then I'd go in Acrobat 5, open to the top of my invoice PDF 1 page document, can I use the shape tool, insert the icon and select my right to 'support' on the 1st page PDF document.  If necessary, I could resize and place anywhere on the paper invoice/PDF 1 existing page that I started with, then the resolution is great (i.e. without "grainy" appearances, etc.).

    I've now upgraded to Acrobat Pro XI (Finally, technically I'm test to ensure he'll will meet my needs - well, until I came across this).  I tried to copy the data Excel directly in my invoice PDF document, but it's often times the super object large (away from the page from left to right) and then I have to resize (significantly smaller) in order to adapt it to the page.  This causes the resizing of the text that should appear "grainy".

    So pretend that my original invoice/PDF 1 page document took the top 1/2 of the page.  Then, in Excel I create a backup that is say 5-10 lines of calculations.  How can I get the Excel save as Image in my document 1 original page (and on the 1 page)?  The only work that I found so far about is to be inserted as the last past, then to highlight the new features in Excel, cut and copy on page 1 (these seems like extra stages in my eyes, but it does not work).

    I also want to avoid using the screen snip-it, snagit and several other tools for the following reasons:

    1. I don't want to remove the gridlines in Excel (that is, when you print from Excel, the grid lines do not print by default)

    2. I use Broadgun PDF to generate a PDF file (i.e. electronic print) and then the document/data looks exactly as I want it to look like if I had printed physically

    Any thoughts?  Thanks in advance for help also.

    Other details: Windows 7 Pro, use of the company

    I don't see what the problem is with the print to PDF using the Adobe PDF printer as you did with the other tool. Open your new PDF Excel, then do the same process as before (assuming that it worked for you). Just go to tools > Interactive and add a button field (I assume that's what you did before) and place the file there. At least give it a try because I think that's what you say you used to do.

  • How to remove the existing PDF file password?

    I use Acrobat 6.0 and would like to know how to remove the password for existing PDF file.

    When I try to open the PDF file and save under a different name, it wouldn't work.

    Does anyone have any suggestions?

    Thanks in advance for your suggestions

    File > properties. Then under security change security None method; Enter the password when you are prompted. Then save under.

  • How to remove unused bookmarks of a PDF?

    I'm trying to find a way to automatically delete the bookmarks of a PDF document if they attach "named destination" no longer exists in the document.

    I thought I could loop through bookmarks, run them, and they threw an error then the bookmark can be deleted, but it did not work IE. no exception is thrown. Here is my code:

    myBookmarks var = this.bookmarkRoot.children;

    for (var i = 0; i < myBookmarks.length; i ++)

    Try

    {

    myBookmarks [i] is [i] myBookmarks .execute ();.

    }

    catch (MonErreur)

    {

    myBookmarks [i] is [i] myBookmarks .remove ();.

    }

    Someone has ideas how to do? Thank you very much. HJ

    At the beginning of the loop, you can set the current view something you know is not the destination of a bookmark (for example, page = 0, zoom = 1234), run the bookmark, and if the view is different, it would be an indication that the bookmark is valid.

  • Modify existing PDF

    Hi all

    I'm working on console application c#, which is used to edit existing pdf files, by moving the paragraphs of the pdf document down, adding text style... etc.

    1. is there a way I can do it with the acrobat SDK? Regarding that I am to change an existing pdf file that is to say the new result will overwrite the old...

    2. is there a kind of dll, what can I use in my application to launch Acrobat Pro XI so that I can use in my project?

    Thank you

    What you can do in Acrobat can easily be automated. There are

    different API in the Acrobat SDK kit and the interface of the IAC has serious

    limitations. Some of them you can move using JavaScript

    Bridge, but still, you will not have access to page content. Only a plug-in

    can access this data and move "paragraphs" is still a huge

    tasks. The PDF file does not organize its content in terms of words,

    sentences or paragraphs, so you should have provide features that

    would be able to identify what you consider as a paragraph. This is not

    a trivial task. You should be able to export your PDF content as a Word

    the document, then do all that 'magical' in Word and then convert the document

    back to PDF (or go directly to the original document and do all the work)

    that).

    Karl Heinz Kremer

    PDF acrobatics without a net

    [email protected]

    http://www.khkonsulting.com

  • Why my favorites so quickly disappear when I try to find one I want to use

    Question
    Why my favorites so quickly disappear when I try to find one I want to use

    Try pressing Ctrl + Shift + B it will open a window with all your bookmarks. I hope this can help you.

Maybe you are looking for