Adding text to PDF using iText instead of CFPDF

Hi,
I know this may seem a bit off topic being posted here but i'm asking this board since i'm a complete JAVA noob and i figure some of you CF folk might have had to do this before.
Anyway, about my question...i'm already adding a watermark image to a pdf using iText (CF8) thanks to the help of fellow poster (=cfSearching=).  What i'm looking for is the best way to go about adding some text to this same pdf.  I need to add 4 lines of text (with specific font and size) and center it underneath the added image.   Does anyone have a site they could point me to as to how to add formatted text and how to get the width of that text so as to align it correctly?  I've search Google and looked at a lot of JAVA code but being a JAVA noob it's tough to figure out exactly which libs and methods can be used to do this. 
Any help would be greatly appreciated!
-Michael

Hi again!
Well, the merged image is an idea but i'd rather have it be actual text so that it is at least copy/paste-able if viewed on a computer.
The four lines of text are dynamic (company name, broker name, phone number, email address) and limited to 40 characters.  Right now they are being added via CFPDF and DDX and use the following code in the DDX file to add it to the PDF.
<PDF result="DestinationFile">
     <PDF source="SourceFile">
          <Watermark
          rotation="0"
          opacity="100%"
          horizontalAnchor="#horzAnchor#"
          horizontalOffset="#horzOffset#"
          verticalAnchor="#vertAnchor#"
          verticalOffset="#vertOffset#"
          alternation="OddPages"
          >
               <StyledText text-align="center">
                    <p font="#font#" color="#color#" >#left(dCompany,maxlinechars)#</p>
                    <p font="#font#" color="#color#" >#left(dName,maxlinechars)#</p>
                    <p font="#font#" color="#color#" >#left(dPhone,maxlinechars)#</p>
                    <p font="#font#" color="#color#" >#left(dEmail,maxlinechars)#</p>
               </StyledText>
          </Watermark>
     </PDF>
</PDF>
Then using the created pdf from above, i use a slightly modified version of the cfscript code ( that uses iText) you provided me previously to add a logo image just above this text.  The only changes i made to it were resizing of the image and adding where to place it.  Here is that code:
<cfscript>                    
    fullPathToInputFile = "#tempdestfilepath#";
     writeoutput("<br>fullPathToInputFile=#fullPathToInputFile#");
    fullPathToWatermark = osFile("#request.logofilepath##qord.userlogo_file#",request.os);
     writeoutput("<br>fullPathToWatermark=#fullPathToWatermark#");
    fullPathToOutputFile =  "#destfilepath#";
     writeoutput("<br>fullPathToOutputFile=#fullPathToOutputFile#");
     ppi = 72; // points per inch
     watermark_x =  ceiling(#qord.pdftemplate_logo_x# * ppi);      // from bottom left corder of pdf
     watermark_y =  ceiling(#qord.pdftemplate_logo_y# * ppi);     // from bottom left corder of pdf
     fh = ceiling(0.75 * ppi);
     fw = ceiling(1.75 * ppi);
   if( not fileexists(fullPathToInputFile) )
              savedErrorMessage = savedErrorMessage & "<li>Input file pdf for logo add does not exist<br>#fullPathToInputFile#</li>";
   else
             try {
             // create PdfReader instance to read in source pdf
             pdfReader = createObject("java", "com.lowagie.text.pdf.PdfReader").init(fullPathToInputFile);
             totalPages = pdfReader.getNumberOfPages();
             // create PdfStamper instance to create new watermarked file
             outStream = createObject("java", "java.io.FileOutputStream").init(fullPathToOutputFile);
             pdfStamper = createObject("java", "com.lowagie.text.pdf.PdfStamper").init(pdfReader, outStream);
             // Read in the watermark image
             img = createObject("java", "com.lowagie.text.Image").getInstance(fullPathToWatermark);
                w = img.scaledWidth();
               h = img.scaledHeight();
               //$is[0] = w
               //$is[1] = h
               if( w >= h )
                  orientation = 0;
              else
                  orientation = 1;
                  fw = max_h;
                  fh = max_w;
              if ( w > fw || h > fh )
                  if( ( w - fw ) >= ( h - fh ) )
                      iw = fw;
                      ih = ( fw / w ) * h;
                  else
                      ih = fh;
                      iw = ( ih / h ) * w;
                  t = 1;
              else
                  iw = w;
                  ih = h;
                  t = 2;
             // adding content to each page
             i = 0;
             //while (i LT totalPages) {
                 i = i + 1;
                 content = pdfStamper.getOverContent( javacast("int", i) );
                 img.setAbsolutePosition(javacast("float", watermark_x), javacast("float", watermark_y));
                    if(t==1)
                         img.scaleAbsoluteWidth( javacast("float", iw) );
                         img.scaleAbsoluteHeight( javacast("float", ih) );
                 content.addImage(img);
                 WriteOutput("Watermarked page "& i &"<br>");
             //WriteOutput("Finished!");
             catch (java.lang.Exception e) {
             savedErrorMessage = savedErrorMessage & "<li>#e#</li>";
         // closing PdfStamper will generate the new PDF file
         if (IsDefined("pdfStamper")) {
             pdfStamper.close();
         if (IsDefined("outStream")) {
             outStream.close();
</cfscript>
The above code resized the image to a certain width/height if needed and adds it to the pdf. 
I just figured they might be a way to tap into one of the java objects that would allow adding the text.  Ideally, adding the text and image to some sort of 'bounding box' that would allow centering of the image and text in relation to that bounding box.  Or if there is no way to add to a bounding box, a way to get the horizontal length of the longest line of text so i could calculate a common centerline for the image and text.
I've attached the following pdf to show how the image and text would look together.  This example is not to scale but a similar image and text would be added to a separate pdf.
Thanks for you help.

Similar Messages

  • Adding a link in PDF using itext

    I am adding a link in PDF using itext and opening the link from the final created pdf using app.launchURL and app.getURL
    it works fine on windows XP but does nothing on MAC OSX /IOS

    Hi Lynn
    And here I was about to suggest you review the link below.
    Silly me.
    Click
    here to read the article
    Sincerely... Rick

  • Problem while generating PDF using iText

    Hi:
    I have generated PDF using iText, where i have written all code in sequential flow.
    <code>
    com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4, 55, 5, 20, 20);
    OutputStream outputstream = response.getOutputStream();
    PdfWriter.getInstance(document,outputstream);
    </code>
    And i have added all fields in the document.
    But my problem is how to display total pagecount on all pages e.g.1\20 (because i have generated PDF sequentially)
    Also i want to add watermark on all pages.
    So, can any body help me to solve this problem?
    Thank You,
    Balaji

    sabre150 wrote:
    Maybe http://itext-general.2136553.n4.nabble.com/
    Nice pron link in there :/

  • Extract Text from pdf using C#

    Hi,
    We are Solution developer using Acrobat,as we have reuirement of extracting text from pdf using C# we have downloaded adobe sdk and installed. We have found only four exmaples in C# and those are used only for viewing pdf in windows application. Can you please guide us how to extract text from pdf using SDK in C#.
    Thanks you for your help.
    Regards
    kiranmai

    Okay so I went ahead and actually added the text extraction functionality to my own C# application, since this was a requested feature by the client anyhow, which originally we were told to bypass if it wasn't "cut and dry", but it wasn't bad so I went ahead and gave the client the text extraction that they wanted. Decided I'd post the source code here for you. This returns the text from the entire document as a string.
           private static string GetText(AcroPDDoc pdDoc)
                AcroPDPage page;
                int pages = pdDoc.GetNumPages();
                string pageText = "";
                for (int i = 0; i < pages; i++)
                    page = (AcroPDPage)pdDoc.AcquirePage(i);
                    object jso, jsNumWords, jsWord;
                    List<string> words = new List<string>();
                    try
                        jso = pdDoc.GetJSObject();
                        if (jso != null)
                            object[] args = new object[] { i };
                            jsNumWords = jso.GetType().InvokeMember("getPageNumWords", BindingFlags.InvokeMethod, null, jso, args, null);
                            int numWords = Int32.Parse(jsNumWords.ToString());
                            for (int j = 0; j <= numWords; j++)
                                object[] argsj = new object[] { i, j, false };
                                jsWord = jso.GetType().InvokeMember("getPageNthWord", BindingFlags.InvokeMethod, null, jso, argsj, null);
                                words.Add((string)jsWord);
                        foreach (string word in words)
                            pageText += word;
                    catch
                return pageText;

  • How to write special characters in PDF using iText

    How to write special characters encoded with UTF-8 in PDF using iText.
    Regards,
    Pandharinath.

    I don't know what your problem is but that's almost certainly the wrong question to ask about it. Java (including iText) uses only Unicode characters. (You may consider some of them to be "special" if you like but Unicode doesn't.) And when it does that, they aren't encoded in UTF-8 or any other encoding.
    So can you describe your problem? That question doesn't make sense.

  • Creating PDF using ITEXT API's - error

    Hi,
    In my WebDynpro Application I want to generate a PDF (using ITEXT API's) out of the data retrieved from back end system .
    I used this source code.
    Document document = new Document(PageSize.A4);
    document.open();
    PdfPTable table = new PdfPTable(1);
    PdfPCell cell;
    cell = new PdfPCell(new Paragraph("ONE"));
    table.addCell(cell);
    cell = new PdfPCell(new Paragraph("TWO"));      
    table.addCell(cell);
    document.add(table);
    document.close();
    byte[] b = new byte[100 * 1024];
    b =  document.toString().getBytes("UTF-8");
    IWDCachedWebResource pdfRes = WDWebResource.getPublicCachedWebResource(b, WDWebResourceType.PDF, WDScopeType.CLIENTSESSION_SCOPE,      wdThis.wdGetAPI().getComponent().getDeployableObjectPart(),"FileNameHelloText"));
    I have used Window Manager to create a external window with the URL from pdfRes.getUrl() method.
    After execution i get a pop up window with out PDF document.
    Please let me know your thoughts & solutions to the above mentioned problem.
    Thanks
    Senthil

    Hello Folks,
                   Use the following snippet of the code to generate PDF using ITEXT API.
                                       Document document = new Document(PageSize.A4);
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         PdfWriter.getInstance(document, bos);
         document.open();
                    PdfPTable table = new PdfPTable(1);
                    PdfPCell cell;
                    cell = new PdfPCell(new Paragraph("ONE"));
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph("TWO"));      
                    table.addCell(cell);
                    document.add(table);
                    document.close();
                    byte [] byteContent = bos.toByteArray();
         IWDCachedWebResource cachedResource =
                             WDWebResource.getPublicCachedWebResource(
              byteContent,
              WDWebResourceType.PDF,
              WDScopeType.CLIENTSESSION_SCOPE,
              wdThis
                                          .wdGetAPI()
                                          .getComponent()
                                          .getDeployableObjectPart(),
              "TestPDF");
                  IWDWindow externalWindow =
            wdComponentAPI
                            .getWindowManager()
                            .createExternalWindow(cachedResource.getURL(),                         "PDF Window",true);
                  externalWindow.open();
    Thanks and Regards,
    Gopi

  • How to read line number text from PDF using plugin?

    Hi, I would like to know how to read line number text from PDF using plugin?
    Thanks in advance.

    Ok, some background reading of the PDF Reference will help you understand why this is so difficult. PDF files are not organised into lines. It is best to think of each word or character on the page as being a graphic with its own position. The human eye sees lines where a series of graphics (words) are roughly in the same horizontal region.
    In the general case it is difficult or even impossible to answer this. You may have columns with different spacing (but the PDF stores no information on what is a column). You may have subscripts and superscripts. You may have text in graphics coinciding with other text. Commonly, there may be titles, headings or page numbers which are just ordinary text and might count as lines.
    That said, what you need to do is extract the text on the page and its positions. The WordFinder APIs are the way to do that. Now, sort all the words out, using the Y coordinates and size to try and guess what makes a "line". Now you are in a position to find the text (divided into words, not strings) and report the "line number" you have estimated.

  • Japanese text from jsp to pdf using itext

    I am using itext for pdf export in my application.
    It works well for english text.But I have pages in japanese also.
    when i export japanese pages to pdf it shows ??? in pdf files.

    Install Google at your machine, enter the following keywords "java", "pdf" and "api" in that input field, hit the submit button and explore the results.

  • Vertical Text in PDF using CFDOCUMENT

    I am using font tag in a CSS file to layout a table header
    using vertical text. In HTML, the vertical text looks fine.
    However, when I convert the table to a pdf using
    <cfdocument>, the vertical text is displayed as horizintal
    text and does not follow the css specified font family, color or
    size.
    Here is the line in the CCS I am referencing:
    .header_vertical {FONT-WEIGHT: bold; FONT-SIZE: 8pt;
    FONT-STYLE: normal; writing-mode:tb-rl; FONT-FAMILY: helvetica,
    arial, verdana, sans-serif; TEXT-DECORATION: none; COLOR: #0f437c}
    This is CFMX7 on a Windows Server 2003 OS running IIS.
    Any ideas???
    Thanks.

    Hi there, did you find a solution to this?
    I had the same issue and no matter what i tried it didn't
    work. I found out that CFDOCUMENT doesn't support CSS2.
    Eventually I came up with a clunky solution, but had no other
    choice. I bought some imaging software called Alagad (
    http://www.alagad.com) which
    produces the vertical text as images on the fly. Its not ideal, but
    there was no ther way I could disply the text.
    Hope this helps you.
    Ally

  • Adding text to PDF form Text field

    Hello there,
    i'm trying add text to textfield in PDF programatically using java.
    if text  contain "(" or ")" brakets are not displaying in PDF textfiled,if i convert "(" to "[" then the text is displaying in the pdf textfield.how do I allow "(" inside text.and i'm creating pdf programatically in java.
    thanks in advance

    hi there,
    finally I figer out the problem that was causing,
    PDF use's  escape character "\" in front of "(" in the text.
    so i replace "(" with "\\ (" in the String using java,that fixes my problem.
    thanks 

  • InvalidPDFHeaderSignature Exception while opening pdf using itext jar

    Hi,
    I am getting InvalidPDFHeader while opening pdf file using itext jar.
    How to overcome this?
    Thanks,
    Veera

    Please continue in your previous thread: Sample code to dynamically append bytes to pdf
    Mod: I'm locking up.

  • Adding text automatically through use of a button

    Hi there,
    Apologies if this has been asked before. I am creating a form in which a user creates a cost estimate for work done. This is just done by typing the information into a standard text field. At the end of every cost estimate is a standard piece of text, detailing terms and conditions etc which is the same across all estimates. Rather than have the user have to type this in every time, or go to another document to cut and paste, I thought it might be possible to use a button that when clicked adds this standard text to the end of the currenlty selected text field. Is this possible?
    Thanks
    JTH

    Yes, I thought of that - and that may well work.
    But currenlty the amount of original text that is entered before hand is variable, it could be as little as two lines, as many as fifty or more. So it may be that this text needs to be added on the first or second, even third page of the PDF. If my understanding is correct there is no way of linking text boxes across pages (in the way you can in InDesign) so each page will have a separate text box and the onus will be placed on the user to page break their text themselves, meaning that this standard piece of text might need adding to the text box on a different page each time. Agreed, I could add it as default to each page and the user deletes what they don't need but that's a little messy.

  • How do i add images in the header and footer to a PDF using iText

    Hi ,
    I want to add images to the header and footer of every page while i am genrating a pdf i have created a separate class called EndPage which i am instanceiating its default constructor in another class 's button action method.
    The above code genrates a PDF for me however it genrates a file with file size zero bytes and does not open it following is my sample code
    //**********Any Help would be appreciated
    Thank You
    public class My_Class
    public String pdf_action()
    EndPage ep=new EndPage();
    return null;
    }//My_class Ends
    class EndPage extends PdfPageEventHelper
    * Demonstrates the use of PageEvents.
    * @param args no arguments needed
    public EndPage()
    try {
    com.lowagie.text.Document document = new Document(PageSize.A4, 50, 50, 70, 70);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D://proposals/endpage.pdf"));
    writer.setPageEvent(new EndPage());
    document.open();
    String text = "Lots of text. ";
    for (int k = 0; k < 10; ++k)
    text += text;
    document.add(new Paragraph(text));
    document.close();
    catch (Exception de) {
    de.printStackTrace();
    public void onEndPage(PdfWriter writer, Document document) {
    try {
    Rectangle page = document.getPageSize();
    PdfPTable head = new PdfPTable(3);
    for (int k = 1; k <= 6; ++k)
    head.addCell("head " + k);
    head.setTotalWidth(page.width() - document.leftMargin() - document.rightMargin());
    head.writeSelectedRows(0, -1, document.leftMargin(), page.height() - document.topMargin() + head.getTotalHeight(),
    writer.getDirectContent());
    PdfPTable foot = new PdfPTable(3);
    for (int k = 1; k <= 6; ++k)
    foot.addCell("foot " + k);
    foot.setTotalWidth(page.width() - document.leftMargin() - document.rightMargin());
    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
    writer.getDirectContent());
    catch (Exception e) {
    throw new ExceptionConverter(e);
    }

    Hi,
    Thanks for the quick response.
    The problem is that when I keep the logo as a watermark, the pdf is not adjusting itself to include the logo as header.
    But if I add a header text via Tools -> Headers and Footers, the pdf is adjusting itself so that the header text is at the beginning , not overlapping with the contents of pdf.
    But while using logo as watermark, some times overlapping of the pdf contents and logo is happening.
    Is there any way to add a logo in the Header and Footer via the option in Tools -> Headers and Footers
    Thanks,
    Vidhya

  • Can't seem to save non-English as text from PDF using Reader

    I have several PDF documents that were originally generated by OpenOffice from a UTF8-encoded text file. The text is in different languages, e.g. Korean, Arabic, Russian, English. When I open these documents and then "save as text", the resulting text files contain garbage or nothing at all in all cases except for English. Is it possible to extract non-English text from a PDF document using Reader? If not, is there a different product that could be used for this purpose? Thanks much!

    They're using fonts that you don't have on your system so no, it isn't possible with Reader.

  • Outline box when editing text in PDF using v8

    We are running, Windows XP, Acro8 with updates. Created PDF files from within INDCS3. Many of the frames are independent.
    When trying to edit the text using the touchup text tool in Acrobat v8, it outlines complete area on the form which are not the same as the frames in INDCS3.
    Was this something new in v8 and how could this be removed via preferences.
    KPanthen, Albany, NY

    This started happening back in AA6 I think. It is not new.

Maybe you are looking for