Wrapping of Arabic text using Acrofields in Itext 5.5 - itext

I have made a pdf template with a multi-line textbox and have to set some Arabic data in the Acrofields using PDFStamper.
The run direction of text is correct for the first line but it changes when text wrapping occurs.
Please guide.
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class TextFields{
public static final String RESULT1 = "D:/template.pdf";
public static final String RESULT2 = "D:/pdf/result.pdf";
protected int tf;
public TextFields(int tf) {
this.tf = tf;
}
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
FontFactory.registerDirectories();
BaseFont unicode = null;
unicode = BaseFont.createFont("D:/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
stamper.getAcroFields().addSubstitutionFont(unicode);
form.setField("TextBox","اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب");
stamper.close();
reader.close();
}
public static void main(String[] args) throws DocumentException, IOException {
TextFields example = new TextFields(0);
example.manipulatePdf(RESULT1, RESULT2);
}
}

I see that you don't flatten the document. If it's your intention that the document remains interactive, you should instruct iText not to generate any appearances. This can be done like this:
form.setGenerateAppearances(false);
By doing so, you tell the PDF viewer to create the appearances. If the problem persists, the problem resides in the PDF viewer, not at the iText level.
If it's your intention to flatten the form, I fear you've encountered a limitation in the current version of iText. You'll need to use a workaround. Please take a look at the FillFlattenMerge3 example. In this example, we get the position of each field:
AcroFields form = reader.getAcroFields();
positions = new HashMap<String, Rectangle>();
Rectangle rectangle;
Map<String, AcroFields.Item> fields = form.getFields();
for (String name : fields.keySet()) {
rectangle = form.getFieldPositions(name).get(0).position;
positions.put(name, rectangle);
}
We use these positions to draw the contents of the fields at the appropriate place using the ColumnText object instead of using the setField() method:
Rectangle rect = positions.get(name);
Phrase p = new Phrase(value, FONT);
ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
p, rect.getLeft() + 2, rect.getBottom() + 2, 0);
This doesn't solve your problem yet, because the showTextAligned() method doesn't wrap text. Instead of using the showTextAligned() method, you need to use the setRunDirection(), addElement(), setSimpleColumn() and go() method:
ColumnText column = new ColumnText(writer.getDirectContent());
column.setSimpleColumn(rect);
column.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
column.addElement(new Paragraph("اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب", unicode));
column.go();
Now your text will be wrapped properly without breaking the ligatures.

Following code works for me.
I have used p{font-family:"arial";} in test.css.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
public class FillFlattenMerge3 {
public static final String SRC = "C:/templatestnew.pdf";
public static final String DEST = "C:/NewFile.pdf";
public static final Font FONT = new Font(FontFamily.HELVETICA, 10);
protected Map<String, Rectangle> positions;
public static void main(String[] args) throws IOException,
DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new FillFlattenMerge3().manipulatePdf(SRC, DEST);
}
public class Background extends PdfPageEventHelper {
PdfImportedPage background;
public Background(PdfImportedPage background) {
this.background = background;
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContentUnder();
cb.addTemplate(background, 0, 0);
}
}
public void manipulatePdf(String src, String dest)
throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
AcroFields form = reader.getAcroFields();
positions = new HashMap<String, Rectangle>();
Rectangle rectangle;
Map<String, AcroFields.Item> fields = form.getFields();
for (String name : fields.keySet()) {
rectangle = form.getFieldPositions(name).get(0).position;
positions.put(name, rectangle);
}
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(dest));
writer.setPageEvent(new Background(writer.getImportedPage(reader, 1)));
document.open();
PdfContentByte cb = writer.getDirectContent();
process(cb, "TextBox", "<p> اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب اب </p>", writer, document);
document.close();
reader.close();
}
protected void process(PdfContentByte cb, String name, String value,
PdfWriter writer, Document document) throws DocumentException,
IOException {
Rectangle rect = positions.get(name);
// mycode starts
XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
// CSS
CSSResolver cssResolver = helper.getDefaultCssResolver(true);
CssFile cssFile = helper.getCSS(new FileInputStream(
"D:\\Itext_Test\\Test\\src\\test.css"));
cssResolver.addCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.autoBookmark(false);
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, end);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser parser = new XMLParser(worker);
// mycode ends
ColumnText column = new ColumnText(writer.getDirectContent());
column.setSimpleColumn(rect);
column.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
ByteArrayInputStream is = new ByteArrayInputStream(
value.getBytes("UTF-8"));
parser.parse(is);
int status = ColumnText.START_COLUMN;
for (Element e : elements) {
if (ColumnText.isAllowedElement(e)) {
column.addElement(e);
status = column.go();
}
}
}
}

i had same problem. you must recreate your template.pdf by adobe acrobat pro and set the font of your textbox to one of known fonts in your os like arial.
good luck.

Related

PdfContentByte.addTemplate(pdfImportedPage, 0, 0) behaves strangly. Upper text truncated [duplicate]

I have the following problem when printing the pdf file after merge, the pdf documents get cut off.
Sometimes this happens because the documents aren't 8.5 x 11
they might be like 11 x 17.
Can we make it detect the page size and then use that same page size for those documents?
Or, if not, is it possible to have it fit to page?
Following is the code:
package com.sumit.program;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class MergePdf {
public static void main(String[] args) {
try {
List<InputStream> pdfs = new ArrayList<InputStream>();
pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Document1.pdf"));
pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf"));
OutputStream output = new FileOutputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\merge1.pdf");
MergePdf.concatPDFs(pdfs, output, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void concatPDFs(List<InputStream> streamOfPDFFiles,
OutputStream outputStream, boolean paginate) {
Document document = new Document();
try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();
// Create Readers for the pdfs.
int i=1;
while (iteratorPDFs.hasNext()) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
System.out.println("Page size is "+pdfReader.getPageSize(1));
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
i++;
}
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
writer.setCompressionLevel(9);
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
System.out.println("No. of pages "+pdfReader.getNumberOfPages());
i=0;
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
Rectangle r=pdfReader.getPageSize(pdfReader.getPageN(pageOfCurrentReaderPDF+1));
if(r.getWidth()==792.0 && r.getHeight()==612.0)
document.setPageSize(PageSize.A4.rotate());
else
document.setPageSize(PageSize.A4);
document.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
i++;
page = writer.getImportedPage(pdfReader,
pageOfCurrentReaderPDF);
System.out.println("Width is "+page.getWidth());
System.out.println("Height is "+page.getHeight());
cb.newlineText();
cb.addTemplate(page, 0, 0);
// Code for pagination.
if (paginate) {
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520,
5, 0);
cb.endText();
}
}
pageOfCurrentReaderPDF = 0;
}
outputStream.flush();
document.close();
outputStream.close();
System.out.println("Merging of Pdfs is done.......");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen())
document.close();
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Using the Document and PdfWriter class in combination with the addTemplate() method to merge documents is a bad idea. That's not what the addTemplate() method is meant for. You have explicitly or implicitly defined the page size for the Document you are working with. With the addTemplate() method, you add PdfImportedPage instances, and
when you add a new page with the same page size and rotation, you throw away all interactivity that exists in that page, but otherwise all is well,
when you add a new page with a different page size and rotation, you get the result you describe. Because of the difference in size, the imported page and the new page do not match. Parts get cut off, extra margins appear, rotations are different, etc.
This is all explained in chapter 6 of my book. You should use PdfCopy instead of PdfWriter. See for instance the FillFlattenMerge2 example:
Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
document.open();
PdfReader reader;
String line = br.readLine();
// loop over readers
// add the PDF to PdfCopy
reader = new PdfReader(baos.toByteArray());
copy.addDocument(reader);
reader.close();
// end loop
document.close();
In your case, you also need to add page numbers, you can do this in a second go, as is done in the StampPageXofY example:
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte pagecontent;
for (int i = 0; i < n; ) {
pagecontent = stamper.getOverContent(++i);
ColumnText.showTextAligned(pagecontent, Element.ALIGN_RIGHT,
new Phrase(String.format("page %s of %s", i, n)), 559, 806, 0);
}
stamper.close();
reader.close();
Or you can add them while merging, as is done in the MergeWithToc example.
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
PageStamp stamp;
document.open();
int n;
int pageNo = 0;
PdfImportedPage page;
Chunk chunk;
for (Map.Entry<String, PdfReader> entry : filesToMerge.entrySet()) {
n = entry.getValue().getNumberOfPages();
for (int i = 0; i < n; ) {
pageNo++;
page = copy.getImportedPage(entry.getValue(), ++i);
stamp = copy.createPageStamp(page);
chunk = new Chunk(String.format("Page %d", pageNo));
if (i == 1)
chunk.setLocalDestination("p" + pageNo);
ColumnText.showTextAligned(stamp.getUnderContent(),
Element.ALIGN_RIGHT, new Phrase(chunk),
559, 810, 0);
stamp.alterContents();
copy.addPage(page);
}
}
document.close();
for (PdfReader r : filesToMerge.values()) {
r.close();
}
reader.close();
I strongly advise against using PdfWriter to merge documents! It's not impossible if you change the page size and the rotation of the page in the Document class, but you're making it harder on yourself. Moreover: using PdfWriter also throws away all interactivity (links, annotations,...) that exists in the pages you're merging. Your customer may experience that as a bug.

How to search the specific keyword in PDF and highlight using itext PDF

I have a requirement to do below items,
Read the existing PDF file
Search the specific keywords in the PDF
Highlight them in specific color or bold
Save the PDF
and i have to tried below code,
public static void main(String[] args) throws IOException, DocumentException
{
File file = new File(DEST); file.getParentFile().mkdirs();
new BrefingPackageHighlight_Main2().manipulatePdf(SRC, DEST);
}
public void manipulatePdf(String src, String dest) throws IOException, DocumentException
{
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); PdfContentByte canvas = stamper.getOverContent(2); canvas.saveState(); canvas.setColorFill(BaseColor.YELLOW);
canvas.rectangle(200, 786, 5, 5);
canvas.fill();
canvas.restoreState();
stamper.close();
reader.close();
}
the above code only highlights top of the second page. Please provide me samples to search one specific keyword and highlight them alone.

iText : Unable to print mathematical characters like ∈, ∩, ∑, ∫, ∆ √, ∠

I am using iText 4.0.2 version for pdf generation. I have some characters/symbols to print like ∈, ∩, ∑, ∫, ∆ (Mathematical symbols) and many others.
My code :
Document document = new Document(PageSize.A4, 60, 60, 60, 60);
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/adeel/experiment.pdf"));
document.open();
String str = "this string will contains special character like this ∈, ∩, ∑, ∫, ∆";
BaseFont bfTimes = null;
try {
bfTimes = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Font fontnormal = new Font(bfTimes, 12, Font.NORMAL, Color.BLACK);
Paragraph para = new Paragraph(str, fontnormal);
document.add(para);
document.close();
writer.close();
System.out.println("Done!");
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
In the above code I am putting all the symbols in str and generating the pdf file. In place of symbols I tried putting unicode characters in str for the symbols but It didn't worked as well.
Please take a look at the MathSymbols example.
First you need a font that supports the symbols you need. Incidentally, FreeSans.ttf is such a font. Then you need to use the right encoding.
You're using UNICODE, so you need Identity-H as the encoding.
You should also use notations such as \u2208, \u2229, \u2211, \u222b, \u2206. That's not a must, but it's good practice.
This is how it's done:
public static final String DEST = "results/fonts/math_symbols.pdf";
public static final String FONT = "resources/fonts/FreeSans.ttf";
public static final String TEXT = "this string contains special characters like this \u2208, \u2229, \u2211, \u222b, \u2206";
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
Paragraph p = new Paragraph(TEXT, f);
document.add(p);
document.close();
}
The result looks like this: math_symbols.pdf
Important: you should always use the most recent, official version of iText. iText 4.0.2 is not an official version.

itext pdf PageSize.LEGAL_LANDSCAPE.rotate() does not print

I have created a program to write pdf having two page, first page is portrait and second one is landscape. It creates pdf but when I print that file it does not print second page i.e. landscape page.
Below is my code
/******************/
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class TestPDF {
public static void main(String args[]) throws DocumentException, FileNotFoundException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("/home/devang/test.pdf"));
document.setMargins(10.0f, 10.0f, 20.0f, 2.0f);
document.open();
//PAGE1
addFirstPage(document);
//PAGE2
addSecondPage(document);
document.close();
}
public static Document addFirstPage(Document document) throws DocumentException {
document.addTitle("Test PDF");
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.add("Page 1");
paragraph.add("\nPage 1");
paragraph.add("\nPage 1");
paragraph.add("\nPage 1");
paragraph.add("\nPage 1");
document.add(paragraph);
return document;
}
public static Document addSecondPage(Document document) throws DocumentException {
document.setPageSize(PageSize.LEGAL_LANDSCAPE.rotate());
document.newPage();
document.addTitle("Test PDF");
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.add("Page 2");
paragraph.add("\nPage 2");
paragraph.add("\nPage 2");
paragraph.add("\nPage 2");
paragraph.add("\nPage 2");
document.add(paragraph);
return document;
}
}
Thanks in advance.
Replace your code with:
Rectangle a4 = PageSize.A4;
Rectangle a4Landscape = a4.rotate();
document.setPageSize(a4Landscape);

How to insert blank lines in PDF?

I am creating a PDF using iText. I want to insert blank lines between paragraphs and tables.
How can I achieve this?
You can trigger a newline by inserting Chunk.NEWLINE into your document. Here's an example.
public static void main(String args[]) {
try {
// create a new document
Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );
document.open();
document.add( new Paragraph( "Hello, World!" ) );
document.add( new Paragraph( "Hello, World!" ) );
// add a couple of blank lines
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
// add one more line with text
document.add( new Paragraph( "Hello, World!" ) );
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Below is a screen shot showing part of the PDF that the code above produces.
And to insert blank line between tables you can use these both methods
table.setSpacingBefore();
table.setSpacingAfter();
You can use "\n" in Paragraph
document.add(new Paragraph("\n\n"));
You can try a blank phrase:
document.add(new Phrase("\n"));
You can add Blank Line throw PdfContentByte class in itextPdf. As shown below:
package com.pdf.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Ranvijay {
public static final String RESULT = "d:/printReport.pdf";
public void createPdf(String filename) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String email = "ranvijay9286#gmail.com";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nEmail: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(email, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
document.add(tabletmp1);
document.close();
}
/**
* Main method.
*
* #param args
* no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws Exception {
new Ranvijay().createPdf(RESULT);
System.out.println("Done Please check........");
}
}
document.add(new Paragraph(""))
It is ineffective above,must add a blank string, like this:
document.add(new Paragraph(" "));
You can add empty line ;
Paragraph p = new Paragraph();
// add one empty line
addEmptyLine(p, 1);
// add 3 empty line
addEmptyLine(p, 3);
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
You can also use
document.add(new Paragraph());
document.add(new Paragraph());
before seperator if you are using either it is fine.
Instead of using:
document.add( Chunk.NEWLINE );
use this:
document.add(new Paragraph(""));
it makes small space
directly use
paragraph.add("\n");
to add an empty line.
I posted this in another question, but I find using tables with iTextSharp offers a great level of precision.
document.Add(BlankLineDoc(16));
public static PdfPTable BlankLineDoc(int height)
{
var table = new PdfPTable(1) {WidthPercentage = 100};
table = BlankLineTable(table, height);
return table;
}
public static PdfPTable BlankLineTable(PdfPTable table, int height, int border = Rectangle.NO_BORDER)
{
var cell = new PdfPCell(new Phrase(" "))
{
Border = border,
Colspan = table.NumberOfColumns,
FixedHeight = height
};
table.AddCell(cell);
return table;
}
BlankLineTable can be used directly when working with tables
I had to add blank lines after a table and I manage it adding many divs as I need it with a css style with padding-top set it up, like this. I've used a template engine (underscore) to loop through the number of lines I need to add.
<% var maxRow = 30; var pos = items.models.length; %>
<% for( pos; pos < maxRow; pos++ ){ %>
<div class="blankRow"></div>
<% }; %>
My css file:
.blankRow:{ padding-top: 15px;}