Anyone wanna help with iText and my java agent?

Hey all,

Found lots of help on this site to get me started but I really am quite lost. If appropriate, tell me (politely pls) to go learn some more :wink:

Here is the scenario…

-Only for use from the notes client.

-Java agent is being called by LS via a form action.

-I pass in the NoteID (agent.run) and get a handle on the backend doc. for processing (was able in early test to use doc context)

-I have successfully added the itext207.jar to my agent

-I can create very nice tables and add content

-I can save the resulting pdf to a notes document

GOALS:

-add a header and footer on each page (table of data to be repeated for both)

-pagenumbers

-eventually will want to get a document collection and write variable number of rows of data to the pdf

CODE:

Here is the basis of the Java agent: removed most of the content to help shorten it.


import lotus.domino.*;

import java.io.*;

import com.lowagie.text.Font;

import com.lowagie.text.*;

import java.util.*;

import com.lowagie.text.pdf.*;

import java.io.PrintWriter;

import java.math.*;

import java.text.*;

import java.lang.*;

import java.awt.*;

import java.awt.event.*;

import com.lowagie.text.Document;

import com.lowagie.text.DocumentException;

import com.lowagie.text.Rectangle;

import com.lowagie.text.Paragraph;

import com.lowagie.text.pdf.PdfPCell;

import com.lowagie.text.pdf.PdfPTable;

import com.lowagie.text.pdf.PdfWriter;

import com.lowagie.text.Chunk;

import com.lowagie.text.FontFactory;

import com.lowagie.text.Phrase;

import com.lowagie.text.Image;

import com.lowagie.text.html.HtmlWriter;

import com.lowagie.text.pdf.PdfContentByte;

import com.lowagie.text.pdf.RandomAccessFileOrArray;

import com.lowagie.text.pdf.codec.TiffImage;

import com.lowagie.text.Element;

import com.lowagie.text.PageSize;

public class JavaAgent extends AgentBase {

     Label l;

	PdfPCell cell;

	Paragraph p1;

	String tiff_file;

	String imTiff_file;

	String pdf_file;

	String strInPutXMLData;

	String strOutPutImage;

	String PdfWriteDirBase;

      String PdfWriteDir;

      String path;

      Locale locale = Locale.US;

public void NotesMain() {

try {

	Session session = getSession();

AgentContext agentContext = session.getAgentContext();

Agent nAgent = agentContext.getCurrentAgent();

Database db = agentContext.getCurrentDatabase();

String strNoteID = nAgent.getParameterDocID();

lotus.domino.Document doc = db.getDocumentByID(strNoteID);





  String userInput = doc.getItemValueString( "ORD_PO_NUM" );

  if ( userInput == null ) userInput = "Nothing Entered";



  /* make a filename  */

 String fName = userInput + "_CC.pdf"; 

 String filePath=  "C:\\" + fName ;          

  PrintWriter pw = getAgentOutput();



  /* create the pdf doc */

 com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.LETTER);



  /* create a writer to listen to the document */

  PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream(filePath));             

//Set PDF Properties

        	 document.addTitle("XYZ Inc.");

        	 document.addSubject("XYZ Inc.");

        	 document.addCreator("XYZ Inc.");

        	 document.addAuthor("XYZ Inc.");

//START: PDF Document

  document.open();

  document.setMargins(18, 18, 36, 36);



  /* add a page */

  document.newPage(); 	



  // some paragraph of text containing a value from a field on the doc      

  Paragraph myP1 = new Paragraph( "XYZ Inc." , new Font(Font.TIMES_ROMAN,16, Font.BOLD));

  myP1.setAlignment(Element.ALIGN_CENTER);

  document.add(myP1); 



  /* close the document */

  document.close();



  /* create a new document to contain the file */  

  lotus.domino.Document tempDoc=null;

  RichTextItem pdfAttach;

  tempDoc=db.createDocument();           	

  tempDoc.replaceItemValue("Form","TempPDF");           	     

  tempDoc.replaceItemValue("UserInput", userInput + "_CC");        

  pdfAttach = tempDoc.createRichTextItem("PDFAttch");

  pdfAttach.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null, filePath, null);



  /* save the doc */

  tempDoc.save(true, true);

  File fPath = new File(filePath);   

  fPath.delete();

       

} catch(Exception e) {

  e.printStackTrace();

}

}

}


If you wanna still help here is what I have for examples from the iowagie site to do the rest…

http://itext.ugent.be/library/com/lowagie/examples/directcontent/pageevents/EndPage.java

http://itext.ugent.be/library/com/lowagie/examples/directcontent/pageevents/PageNumbersWatermark.java

I just can’t figure out how to make these work (or incorporate them to the project for that matter). Any direction would be greatly appreciated.

Obviously I am a complete newb when it comes to java so please be gentle. Any code examples would be very sweet.

Rewards and bids welcome… LOL!

Thanks all and have a GREAT day!

Subject: Anyone wanna help with iText and my java agent?

Hi

Had a look at your code. It’s good for a newb. looks very professional.

Usually I am quiet lazy so only include this line

import com.lowagie.text.pdf.*;

instead of using all these lines

import com.lowagie.text.Document;

import com.lowagie.text.DocumentException;

import com.lowagie.text.Rectangle;

import com.lowagie.text.Paragraph;

import com.lowagie.text.pdf.PdfPCell;

import com.lowagie.text.pdf.PdfPTable;

import com.lowagie.text.pdf.PdfWriter;

import com.lowagie.text.Chunk;

import com.lowagie.text.FontFactory;

import com.lowagie.text.Phrase;

import com.lowagie.text.Image;

import com.lowagie.text.html.HtmlWriter;

import com.lowagie.text.pdf.PdfContentByte;

import com.lowagie.text.pdf.RandomAccessFileOrArray;

import com.lowagie.text.pdf.codec.TiffImage;

import com.lowagie.text.Element;

import com.lowagie.text.PageSize;

now if you want to use the EndPage and PageNumbersWatermark classes you need to import the package containing those classes. In this case it is :

import com.lowagie.text.pdf.PdfPageEventHelper;

Cheers

Chin Perera

chin.perera@bigpond.com

Subject: RE: Anyone wanna help with iText and my java agent?

Hi Chin,

Thanks for your response…

I did add this line in… but I still don’t seem to know how to incorporate any of the endPage code into my code.

Does this have anything to do with it?

package com.lowagie.examples.directcontent.pageevents;

(can’t add this to the agent without the compiler throwing an error)

And/Or

Do I need to add a new class in my java agent to handle this?

Any chance you can show me how or where to incorporate the EndPage example in my agent?

Thanks again for your help.

Mark

Subject: SOLUTION - Anyone wanna help with iText and my java agent?

Hey all,

I got it working as needed.

I must caveat this by saying that I take no credit for any of the code herein. I have simply researched (mostly the Iowagie site and here) and put the pieces together.

In case someone else would like to use this method I have included my final test code below.

Setup:

-Notes Form with a text field called - SomeText

-Action button on the form to call your Java agent (@Command([ToolsRunMacro];“(your agent)”)

-View to contain holder documents (SELECT Form=“TempPDF”)

-Create the TempPDF form (doesn’t need any fields… just a blank form will do… I suggest setting the launch properties to open first attachment)

-Create the java agent with the code at the end of this post (you will need to add the iText jar file to your agent - Edit Project)

You can get the itext jar file. check for the latest release Entreprenerd — The Book about iText

(Great site… thanks a bunch to those guys.)

//***********************************************

//HERES THE CODE

import lotus.domino.*;

import java.io.*;

import com.lowagie.text.Font;

import com.lowagie.text.*;

import java.util.*;

import com.lowagie.text.pdf.*;

import java.io.PrintWriter;

import java.awt.Color;

import java.io.FileOutputStream;

import com.lowagie.text.Document;

import com.lowagie.text.ExceptionConverter;

import com.lowagie.text.PageSize;

import com.lowagie.text.Paragraph;

import com.lowagie.text.Rectangle;

import com.lowagie.text.pdf.PdfPTable;

import com.lowagie.text.pdf.PdfPageEventHelper;

import com.lowagie.text.pdf.PdfWriter;

import com.lowagie.text.Cell;

import com.lowagie.text.Chapter;

import com.lowagie.text.Document;

import com.lowagie.text.Font;

import com.lowagie.text.FontFactory;

import com.lowagie.text.List;

import com.lowagie.text.ListItem;

import com.lowagie.text.Section;

import com.lowagie.text.Table;

import com.lowagie.text.Chunk;

import com.lowagie.text.Element;

import com.lowagie.text.Image;

import com.lowagie.text.Phrase;

import com.lowagie.text.pdf.BaseFont;

import com.lowagie.text.pdf.PdfContentByte;

import com.lowagie.text.pdf.PdfGState;

import com.lowagie.text.pdf.PdfTemplate;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try {

	

  Session session = getSession();						

  AgentContext agentContext = session.getAgentContext();			

  lotus.domino.Document docCon = agentContext.getDocumentContext();

  Database db = agentContext.getCurrentDatabase();

  lotus.domino.Name uName = session.createName(docCon.getItemValueString("REMOTE_USER"));

  

 String userInput = docCon.getItemValueString( "SomeText" );

  if ( userInput == null ) userInput = "Nothing Entered";

  

  /* make a filename that's based on docid  */

  String fName = docCon.getUniversalID() + ".pdf";        

  String filePath=  "C:\\" + fName ;          

  PrintWriter pw = getAgentOutput();



  /* create the pdf doc */

  com.lowagie.text.Document document = new com.lowagie.text.Document();



  /* create a writer to listen to the document */

  PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream(filePath));   

 writer.setPageEvent(new EndPage());        



 //Set PDF Properties

 document.addTitle("XYZ Inc.");

 document.addSubject("XYZ Inc.");

  document.addCreator("XYZ Inc.");

  document.addAuthor("XYZ Inc.");



  document.open();

  document.setMargins(18, 18, 36, 36);



  // some paragraph of text containing a value from a field on the doc      

  Paragraph myParagraph = new Paragraph( userInput , new Font(Font.HELVETICA,8, Font.BOLD));

  myParagraph.setAlignment(Element.ALIGN_CENTER);

Table t2 = new Table(5, 1);

		t2.setBorderColor(new Color(000, 000, 000));

		t2.setPadding(1);

		t2.setSpacing(0);

		t2.setBorderWidth(1);

		

		t2.addCell("1.1");

		t2.addCell("1.2");

		t2.addCell("1.3");

		t2.addCell("1.4");

		t2.addCell("1.5");

		document.add(t2);



		Table table = new Table(3);

		table.setBorderWidth(0);

		table.setBorderColor(new Color(0, 0, 255));

		table.setPadding(1);

		table.setSpacing(0);

		Cell cell = new Cell("header");

		cell.setHeader(true);

		cell.setColspan(3);

		table.addCell(cell);

		table.endHeaders();

		//

		cell = new Cell(myParagraph);

		cell.setRowspan(2);

		cell.setBorderWidth(3);

		cell.setBorderColor(new Color(255, 0, 0));

		table.addCell(cell);

		table.addCell("1.1");

		table.addCell("2.1");

		table.addCell("1.2");

		table.addCell("2.2");

		table.addCell("cell test1");

		cell = new Cell("big cell");

		cell.setRowspan(2);

		cell.setColspan(2);

		table.addCell(cell);

		table.addCell("cell test2");

		document.add(table);



  /* close the document */

  document.close();



  /* create a new document to contain the file */  

  lotus.domino.Document tempDoc=null;

  RichTextItem pdfAttach;

  tempDoc=db.createDocument();           	

  tempDoc.replaceItemValue("Form","TempPDF");           	     

  tempDoc.replaceItemValue("UserInput", userInput);        

  pdfAttach = tempDoc.createRichTextItem("PDFAttch");

  pdfAttach.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null, filePath, null);



  /* save the doc */

  tempDoc.save(true, true);

  File fPath = new File(filePath);   

  fPath.delete();

  

 

} catch(Exception e) {

  e.printStackTrace();

}

}

public class EndPage extends PdfPageEventHelper {

/** The headertable. */

public PdfPTable table;

/** A template that will hold the total number of pages. */

public PdfTemplate tpl;

/** The font that will be used. */

public BaseFont helv;



public void onOpenDocument(PdfWriter writer, Document document) {

    try {

    	// initialization of the header table

    	

        table = new PdfPTable(2);

      // initialization of the template

        tpl = writer.getDirectContent().createTemplate(100, 100);

        tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100));

        

        // initialization of the font

        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    }

    catch(Exception e) {

        throw new ExceptionConverter(e);

    }

}    

public void onStartPage(PdfWriter writer, Document document) {

    if (writer.getPageNumber() < 3) {

        PdfContentByte cb = writer.getDirectContentUnder();

        cb.saveState();

        cb.setColorFill(Color.pink);

        cb.beginText();

        cb.setFontAndSize(helv, 48);

        cb.showTextAligned(Element.ALIGN_CENTER, "Confidential", document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);

        cb.endText();

        cb.restoreState();

    }

}

public void onCloseDocument(PdfWriter writer, Document document) {

   tpl.beginText();

   tpl.setFontAndSize(helv, 8);

   tpl.setTextMatrix(0, 0);

   tpl.showText("" + (writer.getPageNumber() - 1));

   tpl.endText();

}

public void onEndPage(PdfWriter writer, Document document) {

    try {

    PdfContentByte cb = writer.getDirectContent();

    cb.saveState();

    

    table.setTotalWidth(document.right() - document.left());

    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 50, cb);

    // compose the footer

    String text = "Page " + writer.getPageNumber() + " of ";

    float textSize = helv.getWidthPoint(text, 8);

    float textBase = document.bottom() - 20;

    cb.beginText();

    cb.setFontAndSize(helv, 8);

    float adjust = helv.getWidthPoint("0", 12);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);

    cb.showText(text);

    cb.endText();

    cb.addTemplate(tpl, document.right() - adjust, textBase);

    cb.saveState();

        

     // Add the header table

    Rectangle page = document.getPageSize();

   PdfPTable head1 = new PdfPTable(1);

    

   Paragraph myP1 = new Paragraph( "Company Name" , new Font(Font.TIMES_ROMAN,16, Font.BOLD));

    myP1.setAlignment(Element.ALIGN_CENTER);

    PdfPCell cell = new PdfPCell(myP1);

    cell.setHorizontalAlignment(Element.ALIGN_CENTER);

   cell.setBorder(0);

    head1.addCell(cell);

            

    head1.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());

    head1.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - 10, writer.getDirectContent());





      // Add the footer table  

     PdfPTable foot = new PdfPTable(1);

     

     foot.addCell("What ever you want I suppose");

     foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());

     foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin() + 25,

     writer.getDirectContent());

     }    

     catch (Exception e) {

        throw new ExceptionConverter(e);

    }

}

}

}

There should be enough examples to get most anyone started.

Cheers,

Mark

Things you

Subject: RE: SOLUTION - Anyone wanna help with iText and my java agent?

Hi Mark,

Is there any way that a notes document exported to MS Word can be converted to PDF using iText? If yes, how can it be done?

Thanks in advance.

Subject: KUDOS to your SOLUTION - Anyone wanna help with iText and my java agent?

Mark,

Kudos to you posting this, it was a huge help to me incorporating a header into my agent. This is the best example I’ve found so far in regards to incorporating the iText library into my Notes Java AGENT.

I’m currently working on a similar AGENT at work and will post it as well. Hopefully more great examples like yours will come out in the future.

Cheers - MJ

Subject: RE: SOLUTION - Anyone wanna help with iText and my java agent?

I’ve worked through all of the examples with iText - I have them working in my Sandbox. Being completely new to using Java in Domino - I’m much more comfortable in Lotusscript… I have a particular dilema that has not been touched but I don’t believe it’s specific to iText…

I have Documents where a substantive portion of the content is in rich text fields. They are typically text with graphics interspersed, so in outputting this to my pdf using the iText libararies I need to preserve this formatting. While using PDFWriter to simply ‘print’ the docs works well, it is the very use of PDFWriter and Adobe Acrobat that I’m trying to get away from.

Can anyone provide a pointer to the relevant technique in a java agent to course through and/or dissect my Rich Text Field for output to the pdf?

Am I in a situation where I should be reading about XSL-FO and such?

Thanks in advance,

DWConnell