I'm producing PDF reports using the iTextSharp library. I have a paragraph as title with a line underneath.
When I add an PdfPageEventHelper class as PageEventListener to my writer which handles the background and page numbering on each page, the line disappears. I think it's about the alignment of the background and the line so the line is behind the background but I can't seem to arrange it in front.
Document code:
using (Document doc = new Document())
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=IVIPS_report.pdf");
doc.SetPageSize(PageSize.A4.Rotate());
doc.SetMargins(36f, 36f, 36f, 70f);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
bckgr = Image.GetInstance(Request.MapPath(PDF_BACKGROUND_LANDSCAPE_PATH));
bckgr.Alignment = Image.UNDERLYING;
bckgr.SetAbsolutePosition(0, 0);
bckgr.ScaleToFit(doc.PageSize);
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
MyPdfPageEventHelpPageNo PdfPageEvent = new MyPdfPageEventHelpPageNo();
writer.PageEvent = PdfPageEvent;
doc.Open();
Font title = new Font(Font.FontFamily.HELVETICA, 16f, Font.BOLD, BaseColor.DARK_GRAY);
Paragraph p = new Paragraph("Overzicht chauffeurs", title);
p.Alignment = Element.ALIGN_LEFT;
LineSeparator line = new LineSeparator(1f, 100f, BaseColor.DARK_GRAY, Element.ALIGN_CENTER, -27f);
doc.Add(p);
doc.Add(line);
}
PdfPageEvent code:
public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
document.Add(bckgr);
Font fFooter = new Font(Font.FontFamily.HELVETICA, 9f, Font.NORMAL, BaseColor.GRAY);
Rectangle page = document.PageSize;
PdfPTable pageFooter = new PdfPTable(1);
pageFooter.TotalWidth = page.Width;
Phrase pagenr = new Phrase("Gegenereerd op " + DateTime.Now.ToString("dd/MM/yyyy") + " - Pagina " + document.PageNumber, fFooter);
PdfPCell c = new PdfPCell(pagenr);
c.Border = Rectangle.NO_BORDER;
c.VerticalAlignment = Element.ALIGN_BOTTOM;
c.HorizontalAlignment = Element.ALIGN_CENTER;
pageFooter.AddCell(c);
pageFooter.WriteSelectedRows(0, -1, 0, 25, writer.DirectContent);
}
}
Related
This question is a follow-up from this
After the previous post I managed to create the following method that fits text in certain spaces in paragraphs.
public static void getPlainFill2(String str, Document doc, PdfDocument document, Paragraph root,
Paragraph space, boolean isCentred) {
// System.out.println("prevText: "+prev.getText());
float width = doc.getPageEffectiveArea(PageSize.A4).getWidth();
float height = doc.getPageEffectiveArea(PageSize.A4).getHeight();
if (str.isEmpty() || str.isBlank()) {
str = "________";
}
IRenderer spaceRenderer = space.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult spaceResult = spaceRenderer
.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width, height))));
Rectangle rectSpaceBox = ((ParagraphRenderer) spaceRenderer).getOccupiedArea().getBBox();
float writingWidth = rectSpaceBox.getWidth();
float writingHeight = rectSpaceBox.getHeight();
Rectangle remaining = doc.getRenderer().getCurrentArea().getBBox();
float yReal = remaining.getTop() + 2f;// orig 4f
float sizet = 0;
for (int i = 0; i < root.getChildren().size(); i++) {
IElement e = root.getChildren().get(i);
if (e.equals(space)) {
break;
}
IRenderer ss = e.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult ss2 = ss.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width, height))));
sizet += ss.getOccupiedArea().getBBox().getWidth();
System.out.println("width: " + width + " current: " + sizet);
}
float start = sizet+doc.getLeftMargin();
if(isCentred)
start = (width - getRealWidth(doc, root,width,height))/2+doc.getLeftMargin()+sizet;
Rectangle towr = new Rectangle(start, yReal, writingWidth, writingHeight);// sizet+doc.getLeftMargin()
PdfCanvas pdfcanvas = new PdfCanvas(document.getFirstPage());
Canvas canvas = new Canvas(pdfcanvas, towr);
canvas.setTextAlignment(TextAlignment.CENTER);
canvas.setHorizontalAlignment(HorizontalAlignment.CENTER);
Paragraph paragraph = new Paragraph(str).setTextAlignment(TextAlignment.CENTER).setBold();//.setMultipliedLeading(0.9f);
Div lineDiv = new Div();
lineDiv.setVerticalAlignment(VerticalAlignment.MIDDLE);
lineDiv.add(paragraph);
float fontSizeL = 1f;
float fontSizeR = 12;
int adjust = 0;
while (Math.abs(fontSizeL - fontSizeR) > 1e-1) {
float curFontSize = (fontSizeL + fontSizeR) / 2;
lineDiv.setFontSize(curFontSize);
// It is important to set parent for the current element renderer to a root
// renderer
IRenderer renderer = lineDiv.createRendererSubTree().setParent(canvas.getRenderer());
LayoutContext context = new LayoutContext(new LayoutArea(1, towr));
if (renderer.layout(context).getStatus() == LayoutResult.FULL) {
// we can fit all the text with curFontSize
fontSizeL = curFontSize;
} else {
fontSizeR = curFontSize;
}
if(adjust>=2) {
writingHeight -=1.3f;
yReal += 1.4f;
adjust= 0;
}
}
lineDiv.setFontSize(fontSizeL);
canvas.add(lineDiv);
// border
// PdfCanvas(document.getFirstPage()).rectangle(towr).setStrokeColor(ColorConstants.BLACK).stroke();
canvas.close();
}
public static float getRealWidth (Document doc, Paragraph root,float width,float height) {
float sizet = 0;
for(int i = 0;i<root.getChildren().size();i++) {
IElement e = root.getChildren().get(i);
IRenderer ss = e.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult ss2 = ss.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width,height))));
sizet +=ss.getOccupiedArea().getBBox().getWidth();
}
return sizet;}
Now this works almost decent, there are minor issues when text scales to lower sizes and it goes like:
https://i.ibb.co/MkxfwjQ/Screenshot-from-2021-06-14-18-27-09.png (I can't post images because I have no rep.)
but the main issue is that you have to write Paragraphs line by line to work. As next example:
Cell cell3 = new Cell();
LineCountingParagraph line3 = new LineCountingParagraph("");
Text ch07 = new Text("Paragraph Prev ");
line3.add(ch07);
Paragraph nrZile = getEmptySpace(15);
line3.add(nrZile);
Text ch08 = new Text("afterStr, textasdsadasdas ");
line3.add(ch08);
Paragraph data = getEmptySpace(18);
line3.add(data);
Text ch09 = new Text(".\n");
line3.add(ch09);
line3.setTextAlignment(TextAlignment.CENTER);
cell3.add(line3);
doc.add(cell3);
getPlainFill2("thisisalongstring", doc, document, line3, nrZile, true);
getPlainFill2("1333", doc, document, line3, data, true);
Cell cell4 = new Cell();
LineCountingParagraph line4 = new LineCountingParagraph("");
Paragraph loc2 = getEmptySpace(30);
line4.add(loc2);
Text pr32 = new Text(" aasdbsadasd ");
line4.add(pr32);
Paragraph nr2 = getEmptySpace(8);
line4.add(nr2);
Text pr33 = new Text(" asdasdasdasd.\n");
line4.add(pr33);
line4.setTextAlignment(TextAlignment.CENTER);
cell4.add(line4);
doc.add(cell4);
getPlainFill2("1333", doc, document, line4, nr2, true);
If you need more code, I'll upload it somewhere.
Now is there a way to insert text within the same paragraph on multiple lines ? because there seems I cannot find a way to detect line break in IText 7.1.11.
Full code:
package pdfFill;
import java.io.File;
import java.io.IOException;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Div;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.layout.LayoutArea;
import com.itextpdf.layout.layout.LayoutContext;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;
import com.itextpdf.layout.renderer.ParagraphRenderer;
public class Newway4 {
public static void main(String[] args) {
PdfWriter writer;
try {
writer = new PdfWriter(new File("test4.pdf"));
PdfDocument document = new PdfDocument(writer);
document.getDocumentInfo().addCreationDate();
document.getDocumentInfo().setAuthor("Piri");
document.getDocumentInfo().setTitle("Test_Stackoverflow");
document.setDefaultPageSize(PageSize.A4);
Document doc = new Document(document);
doc.setFontSize(12);
final Paragraph titlu = new Paragraph();
final Text t1 = new Text("\n\n\n\nTest Stackoverflow\n\n\n").setBold().setUnderline();
titlu.setHorizontalAlignment(HorizontalAlignment.CENTER);
titlu.setTextAlignment(TextAlignment.CENTER);
titlu.add(t1).setBold();
doc.add(titlu);
Cell cell1 = new Cell();
LineCountingParagraph line1 = new LineCountingParagraph("");
line1.add( addTab());
Text ch01 = new Text("This is the 1st example ");
line1.add(ch01);
Paragraph name = getEmptySpace(42);
line1.add(name);// cnp new line
Text ch02 = new Text(" that works ");
line1.add(ch02);
Paragraph domiciliu = getEmptySpace(63);
line1.add(domiciliu);
/* Text ch03 = new Text("\njudet");
line1.add(ch03);
Paragraph judet = getEmptySpace(12);
line1.add(judet);*/
Text ch031 = new Text("\n");
line1.add(ch031);
cell1.add(line1);
doc.add(cell1);
getPlainFill2("with insertion str", doc, document, line1, name, false);
getPlainFill2("because is writtin line by line", doc, document, line1, domiciliu, false);
Cell cell2 = new Cell();
LineCountingParagraph line2 = new LineCountingParagraph("");
Text p51 = new Text("as you can see in this");
line2.add(p51);
Paragraph localitatea = getEmptySpace(30);
line2.add(localitatea);
Text p7 = new Text(" and ");
line2.add(p7);
Paragraph nrCasa =getEmptySpace(8);
line2.add(nrCasa);
Text p09 = new Text(" of text scalling ");
line2.add(p09);
Paragraph telefon = getEmptySpace(22);
line2.add(telefon);
Text p11 = new Text(".");
line2.add(p11);
line2.setTextAlignment(TextAlignment.CENTER);
cell2.add(line2);
doc.add(cell2);
getPlainFill2("sentence", doc, document, line2, localitatea, true);
getPlainFill2("example", doc, document, line2, nrCasa, true);
getPlainFill2("text scalling bla bla", doc, document, line2, telefon, true);
doc.add(new Paragraph("\n\n\n"));
LineCountingParagraph paragraphTest = new LineCountingParagraph("");
paragraphTest.add(addTab());
Text testch01 = new Text("This is the 2nd example ");
paragraphTest.add(testch01);
Paragraph emptyTest01 = getEmptySpace(42);
paragraphTest.add(emptyTest01);
Text testch02 = new Text(" that doesn't work ");
paragraphTest.add(testch02);
Paragraph emptyTest02 = getEmptySpace(53);
paragraphTest.add(emptyTest02);
Text testch04 = new Text(" this next goes to the next line but ");
paragraphTest.add(testch04);
Paragraph emptyTest03 = getEmptySpace(42);
paragraphTest.add(emptyTest03);
Text testch05 = new Text(" won't appear !!");
paragraphTest.add(testch05);
doc.add(paragraphTest);
getPlainFill2("with insertion str", doc, document, paragraphTest, emptyTest01, false);
getPlainFill2("because next text goes next line", doc, document, paragraphTest, emptyTest02, false);
getPlainFill2("this text", doc, document, paragraphTest, emptyTest03, false);
doc.close();
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getStrWithDots(final int dots, final String str) {
final int strSize = str.length();
final StringBuilder sb = new StringBuilder();
int dotsRemained;
if (strSize > dots) {
dotsRemained = 0;
} else {
dotsRemained = dots - strSize;
}
for (int i = 0; i < dotsRemained; ++i) {
if (i == dotsRemained / 2) {
sb.append(str);
}
sb.append(".");
}
return sb.toString();
}
public static void getPlainFill2(String str, Document doc, PdfDocument document, Paragraph root,
Paragraph space, boolean isCentred) {
// System.out.println("prevText: "+prev.getText());
float width = doc.getPageEffectiveArea(PageSize.A4).getWidth();
float height = doc.getPageEffectiveArea(PageSize.A4).getHeight();
if (str.isEmpty() || str.isBlank()) {
str = "________";
}
IRenderer spaceRenderer = space.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult spaceResult = spaceRenderer
.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width, height))));
Rectangle rectSpaceBox = ((ParagraphRenderer) spaceRenderer).getOccupiedArea().getBBox();
float writingWidth = rectSpaceBox.getWidth();
float writingHeight = rectSpaceBox.getHeight();
Rectangle remaining = doc.getRenderer().getCurrentArea().getBBox();
float yReal = remaining.getTop() + 2f;// orig 4f
float sizet = 0;
for (int i = 0; i < root.getChildren().size(); i++) {
IElement e = root.getChildren().get(i);
if (e.equals(space)) {
break;
}
IRenderer ss = e.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult ss2 = ss.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width, height))));
sizet += ss.getOccupiedArea().getBBox().getWidth();
}
float start = sizet+doc.getLeftMargin();
if(isCentred)
start = (width - getRealWidth(doc, root,width,height))/2+doc.getLeftMargin()+sizet;
Rectangle towr = new Rectangle(start, yReal, writingWidth, writingHeight);// sizet+doc.getLeftMargin()
PdfCanvas pdfcanvas = new PdfCanvas(document.getFirstPage());
Canvas canvas = new Canvas(pdfcanvas, towr);
canvas.setTextAlignment(TextAlignment.CENTER);
canvas.setHorizontalAlignment(HorizontalAlignment.CENTER);
Paragraph paragraph = new Paragraph(str).setTextAlignment(TextAlignment.CENTER).setBold();//.setMultipliedLeading(0.9f);//setbold oprtional
Div lineDiv = new Div();
lineDiv.setVerticalAlignment(VerticalAlignment.MIDDLE);
lineDiv.add(paragraph);
float fontSizeL = 0.0001f, fontSizeR= 10000;
int adjust = 0;
while (Math.abs(fontSizeL - fontSizeR) > 1e-1) {
float curFontSize = (fontSizeL + fontSizeR) / 2;
lineDiv.setFontSize(curFontSize);
// It is important to set parent for the current element renderer to a root
// renderer
IRenderer renderer = lineDiv.createRendererSubTree().setParent(canvas.getRenderer());
LayoutContext context = new LayoutContext(new LayoutArea(1, towr));
if (renderer.layout(context).getStatus() == LayoutResult.FULL) {
// we can fit all the text with curFontSize
fontSizeL = curFontSize;
if (++adjust>1)
towr.setHeight(towr.getHeight()-0.90f);
} else {
fontSizeR = curFontSize;
}
}
lineDiv.setFontSize(fontSizeL);
canvas.add(lineDiv);
new PdfCanvas(document.getFirstPage()).rectangle(towr).setStrokeColor(ColorConstants.BLACK).stroke();
canvas.close();
}
public static Text addTab() {
StringBuilder sb = new StringBuilder();
for(int i = 0;i<8;i++)
sb.append("\u00a0");
return new Text(sb.toString());
}
public static float getRealWidth (Document doc, Paragraph root,float width,float height) {
float sizet = 0;
for(int i = 0;i<root.getChildren().size();i++) {
IElement e = root.getChildren().get(i);
IRenderer ss = e.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult ss2 = ss.layout(new LayoutContext(new LayoutArea(1, new Rectangle(width,height))));
sizet +=ss.getOccupiedArea().getBBox().getWidth();
}
return sizet;
}
private static Paragraph getEmptySpace(int size) {
Paragraph space = new Paragraph();
space.setMaxWidth(size);
for(int i=0;i<size;i++) {
// par.add("\u00a0");
space.add("\u00a0");
}
return space;
}
private static class LineCountingParagraph extends Paragraph {
private int linesWritten = 0;
public LineCountingParagraph(String text) {
super(text);
}
public void addWrittenLines(int toAdd) {
linesWritten += toAdd;
}
public int getNumberOfWrittenLines() {
return linesWritten;
}
#Override
protected IRenderer makeNewRenderer() {
return new LineCountingParagraphRenderer(this);
}
}
private static class LineCountingParagraphRenderer extends ParagraphRenderer {
public LineCountingParagraphRenderer(LineCountingParagraph modelElement) {
super(modelElement);
}
#Override
public void drawChildren(DrawContext drawContext) {
((LineCountingParagraph)modelElement).addWrittenLines(lines.size());
super.drawChildren(drawContext);
}
#Override
public IRenderer getNextRenderer() {
return new LineCountingParagraphRenderer((LineCountingParagraph) modelElement);
}
}
}
The issue: in the top half of the PDF you can see the result of two LineCountingParagraph instances being created, one per line. In the bottom half of the PDF you can see the result when only one instance of LineCountingParagraph is created. So fitting the text in boxes does not work well in case content of the paragraph wraps to the next line.
You have unnecessarily complicated things in such a way that we have to start from scratch :)
So the goal is to be able to create paragraphs with boxed intrusions of fixed width, where we need to copy-fit (place) some text, making sure the font size is selected in such a way that the text fits into that box.
The result should look similar to this picture:
The idea is that we will add paragraphs of fixed width into our main paragraph (iText allows adding block elements and a paragraph is a block element - into paragraphs). The fixed width will be guaranteed by the contents of our paragraph - it will just contain non-breakable spaces. Our paragraph will actually be backed by another paragraph with the actual content we want to fit into our wrapping paragraph. During the layout of the wrapping paragraph we will know its effective boundary and we will just use that area to determine the right font size for our content paragraph using binary search algorithm. Once the right font size has been determined we will just make sure the paragraph with the content gets drawn right next to our wrapping paragraph.
The code for our wrapping paragraph is pretty simple. It just expects the underlying paragraph with real content as the parameter. As always with iText layout, we should customize the renderer of our autoscaling paragraph:
private static class AutoScalingParagraph extends Paragraph {
Paragraph innerParagraph;
public AutoScalingParagraph(Paragraph innerParagraph) {
this.innerParagraph = innerParagraph;
}
#Override
protected IRenderer makeNewRenderer() {
return new AutoScalingParagraphRenderer(this);
}
}
private static class AutoScalingParagraphRenderer extends ParagraphRenderer {
private IRenderer innerRenderer;
public AutoScalingParagraphRenderer(AutoScalingParagraph modelElement) {
super(modelElement);
}
#Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutResult baseResult = super.layout(layoutContext);
this.innerRenderer = ((AutoScalingParagraph)modelElement).innerParagraph.createRendererSubTree().setParent(this);
if (baseResult.getStatus() == LayoutResult.FULL) {
float fontSizeL = 0.0001f, fontSizeR= 10000;
while (Math.abs(fontSizeL - fontSizeR) > 1e-1) {
float curFontSize = (fontSizeL + fontSizeR) / 2;
this.innerRenderer.setProperty(Property.FONT_SIZE, UnitValue.createPointValue(curFontSize));
if (this.innerRenderer.layout(new LayoutContext(getOccupiedArea().clone())).getStatus() == LayoutResult.FULL) {
// we can fit all the text with curFontSize
fontSizeL = curFontSize;
} else {
fontSizeR = curFontSize;
}
}
this.innerRenderer.setProperty(Property.FONT_SIZE, UnitValue.createPointValue(fontSizeL));
this.innerRenderer.layout(new LayoutContext(getOccupiedArea().clone()));
}
return baseResult;
}
#Override
public void drawChildren(DrawContext drawContext) {
super.drawChildren(drawContext);
innerRenderer.draw(drawContext);
}
#Override
public IRenderer getNextRenderer() {
return new AutoScalingParagraphRenderer((AutoScalingParagraph) modelElement);
}
}
Now we add the helper function for creating our wrapper paragraphs that just accepts the desired paragraph width in spaces and the underlying content we want to fit into that space:
private static Paragraph createAdjustableParagraph(int widthInSpaces, Paragraph innerContent) {
AutoScalingParagraph paragraph = new AutoScalingParagraph(innerContent);
paragraph.setBorder(new SolidBorder(1));
StringBuilder sb = new StringBuilder();
for(int i=0;i<widthInSpaces;i++) {
sb.append("\u00a0");
}
paragraph.add(sb.toString());
return paragraph;
}
Finally, the main code:
PdfWriter writer = new PdfWriter(new File("test4.pdf"));
PdfDocument document = new PdfDocument(writer);
Document doc = new Document(document);
Paragraph paragraphTest = new Paragraph();
Text testch01 = new Text("This is the 2nd example ");
paragraphTest.add(testch01);
paragraphTest.add(createAdjustableParagraph(42, new Paragraph("with insertion str")));
Text testch02 = new Text(" that doesn't work ");
paragraphTest.add(testch02);
paragraphTest.add(createAdjustableParagraph(53, new Paragraph("because next text goes next line")));
Text testch04 = new Text(" this next goes to the next line but ");
paragraphTest.add(testch04);
paragraphTest.add(createAdjustableParagraph(42, new Paragraph("this text")));
Text testch05 = new Text(" won't appear !!");
paragraphTest.add(testch05);
doc.add(paragraphTest);
doc.close();
Which gives us the following result:
So we just have the one main paragraph which contains some content and our paragraph wrappers, which in tern have the underlying content we want to fit.
Hint: centering the text is very easy, you don't need to calculate coordinates etc. Just set the right property to the paragraph with the content that you feed to your wrapper paragraph:
paragraphTest.add(createAdjustableParagraph(42, new Paragraph("this text").setTextAlignment(TextAlignment.CENTER)));
And you get the result:
I used iTextSharp and all Turkish character disappeared.
Also html inline css attributes work on table element but not working on div element.
I tried lots of encoding convert sample code but not found any results.
My sample code:
public static byte[] HtmlToPdfItextSharp(string HTMLCONTENTSTRING, List<string> cssFiles = null)
{
using (var ms = new MemoryStream())
{
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
BaseFont STF_Helvetica_Turkish = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, "CP1254", BaseFont.NOT_EMBEDDED);
Font fontNormal = new Font(STF_Helvetica_Turkish, 12, Font.NORMAL, BaseColor.BLACK);
string fontPath = Path.Combine(Path.Combine(Server.MapPath("~/App_Data/Pdf/arial.ttf")));
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.UseUnicode = true;
fontProvider.Register(fontPath);
CssAppliers ca = new CssAppliersImpl(fontProvider);
var pdfWriter = PdfWriter.GetInstance(pdfDoc, ms);
pdfDoc.Open();
pdfWriter.DirectContent.SetFontAndSize(STF_Helvetica_Turkish, 12);
pdfWriter.CloseStream = false;
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssFiles.ForEach(e => cssResolver.AddCssFile(e, true));
var pp = new PdfWriterPipeline(pdfDoc, pdfWriter);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, pp));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(HTMLCONTENTSTRING)));
pdfDoc.Close();
return ms.GetBuffer();
}
}
I updated my code and add stylesheet file (with font familiy:arial;) and i solved character
but it takes too long time
My new updated function like:
public static byte[] HtmlToPdfItextSharp(string HTMLCONTENTSTRING, List<string> cssFiles = null)
{
using (var ms= new MemoryStream())
{
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10, 10, 7, 10);
var pdfWriter = PdfWriter.GetInstance(pdfDoc, ms);
pdfWriter.CloseStream = false;
pdfDoc.Open();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssFiles.ForEach(e => cssResolver.AddCssFile(e, true));
var pp = new PdfWriterPipeline(pdfDoc, pdfWriter);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, pp));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(pHtmlIcerik)));
pdfDoc.Close();
return ms.ToArray();
}
}
Css code :
body {
font-family:Arial;
}
table{
font-family:Arial;
}
td{
font-family:Arial;
}
I have the following Java program to create an iText PDF:
//Create the PDF file
public int CreatePDF(String[] pSrc,
String pDest)
throws IOException
{
//Initialize
ConverterProperties vProperties = new ConverterProperties();
//Adding the fonts
FontProvider vfontProvider = new DefaultFontProvider(false, false, false);
for (String font : FONTS)
{
FontProgram vfontProgram = FontProgramFactory.createFont(font);
vfontProvider.addFont(vfontProgram);
}
vProperties.setFontProvider(vfontProvider);
PdfWriter vWriter = new PdfWriter(pDest, new WriterProperties().setCompressionLevel(9));
PdfDocument vPDF = new PdfDocument(vWriter);
PdfMerger vMerger = new PdfMerger(vPDF);
//Convert to PDF
for (String vHTML : pSrc)
{
ByteArrayOutputStream vArrByteAOS = new ByteArrayOutputStream();
PdfDocument vDoc = new PdfDocument(new PdfWriter(vArrByteAOS, new WriterProperties().setCompressionLevel(9)));
vDoc.setDefaultPageSize(new PageSize(735, 1080));
HtmlConverter.convertToPdf(vHTML, vDoc, vProperties);
vDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(vArrByteAOS.toByteArray())));
vMerger.merge(vDoc, 1, vDoc.getNumberOfPages());
vDoc.close();
}
vPDF.close();
return 0;
}
How can I set the Page Height (now hardcoded to 1080) based on the size of the HTML content (pSrc) in order to ensure that it fits to one page.
I'm using iText to create a PDF in my java spring mvc web project. I'm new to iText 5. Could anyone tell me how to add a text field under a paragraph? Based on my current code, the text field is not displayed under the paragraph. I may add more questions to the PDF so I want to display each text field under the paragraph.
try {
List<FormQuestionBean> questions = formBuilderBean.getQuestions();
MyHeaderAndFooter event = new MyHeaderAndFooter();
Document pdfDocument = new Document(PageSize.A4);
pdfDocument.setMargins(20, 20, 20, 30);
ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(pdfDocument, pdfBaos);
writer.setPageEvent(event);
pdfDocument.open();
Paragraph paragraph1 = new Paragraph(FORM_NAME + " : " + formBuilderBean.getName(), HEADING);
paragraph1.setSpacingAfter(20);
pdfDocument.add(paragraph1);
for (FormQuestionBean formQuestionBean: questions) {
if (formQuestionBean.getFieldImplementation().contentEquals("Text Field")) {
Paragraph p = new Paragraph(formQuestionBean.getName());
pdfDocument.add(p);
TextField text = new TextField(writer, new Rectangle(36, 788, 559, 806), "text" );
text.setBackgroundColor(BaseColor.WHITE);
PdfFormField field = text.getTextField();
writer.addAnnotation(field);
}
}
pdfDocument.close();
response.reset();
response.setHeader("Content-Length", String.valueOf(pdfBaos.size()));
response.setContentType("application/pdf");
response.setContentLength(pdfBaos.size());
String downloadName = getFormFileName(".pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
OutputStream outputStream = response.getOutputStream();
pdfBaos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
return false;
}
I figured out using table and cell. Below is the code:
try {
List<FormQuestionBean> questions = formBuilderBean.getQuestions();
MyHeaderAndFooter event = new MyHeaderAndFooter();
Document pdfDocument = new Document(PageSize.A4);
pdfDocument.setMargins(20, 20, 20, 30);
ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(pdfDocument, pdfBaos);
writer.setPageEvent(event);
pdfDocument.open();
Paragraph paragraph1 = new Paragraph(FORM_NAME + " : " + formBuilderBean.getName(), HEADING);
paragraph1.setSpacingAfter(20);
pdfDocument.add(paragraph1);
for (FormQuestionBean formQuestionBean: questions) {
if (formQuestionBean.getFieldImplementation().contentEquals("Text Field")) {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
PdfPCell c1 = new PdfPCell(new Phrase(formQuestionBean.getName()));
c1.setFixedHeight(30);
table.addCell(c1);
PdfPCell c2 = new PdfPCell();
TextField text = new TextField(writer, c2, "text" );
text.setBackgroundColor(BaseColor.WHITE);
FieldPositioningEvents events = new FieldPositioningEvents(writer, text.getTextField());
c2.setCellEvent(events);
c2.setFixedHeight(30);
table.addCell(c2);
pdfDocument.add(table);
}
}
pdfDocument.close();
response.reset();
response.setHeader("Content-Length", String.valueOf(pdfBaos.size()));
response.setContentType("application/pdf");
response.setContentLength(pdfBaos.size());
String downloadName = getFormFileName(".pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
OutputStream outputStream = response.getOutputStream();
pdfBaos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
return false;
}
I have this code to create TextFields
public void MssCreateTextField(byte[] ssPdf, RCRectangleRecord ssRectangle, string ssName, int ssFontSize, string ssValue, int ssPage, out byte[] ssPdfOut, bool ssIsMultiline) {
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
/*TextField tField = new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle.ssSTRectangle.ssllx, (float)ssRectangle.ssSTRectangle.sslly, (float)ssRectangle.ssSTRectangle.ssurx, (float)ssRectangle.ssSTRectangle.ssury), ssName);
if (ssValue!="")
tField.Text = ssValue;
if (ssIsMultiline)
tField.Options = TextField.MULTILINE;
tField.FontSize = ssFontSize;*/
PdfFormField tField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 50);
tField.FieldName = ssName;
tField.SetWidget(new iTextSharp.text.Rectangle((float)ssRectangle.ssSTRectangle.ssllx, (float)ssRectangle.ssSTRectangle.sslly, (float)ssRectangle.ssSTRectangle.ssurx, (float)ssRectangle.ssSTRectangle.ssury), PdfAnnotation.HIGHLIGHT_TOGGLE);
stamper.FormFlattening = false;
stamper.AddAnnotation(tField, ssPage);
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();
}
As you can see i have some code commented as an alternative but the two different ways are producing the same result.
What i am trying to achieve is create two textfields with the same name to when editing one it edits the others two. This two codes do that (in the browsers and pdfescape site) excepting in the adobe acrobat reader. In the acrobat reader i get just the first field visible and the others hidden i dont know why...
If you want to add two text field visualizations which represent the same content, you have to add them as two widgets of the same field and not two distinct fields, e.g. like this:
public void CreateDoubleTextField(byte[] ssPdf, Rectangle ssRectangle1, Rectangle ssRectangle2, string ssName, int ssFontSize, string ssValue, int ssPage, out byte[] ssPdfOut, bool ssIsMultiline)
{
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
PdfFormField tField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 50);
tField.FieldName = ssName;
PdfFormField widget1 = PdfFormField.CreateEmpty(stamper.Writer);
widget1.SetWidget(ssRectangle1, PdfAnnotation.HIGHLIGHT_TOGGLE);
PdfFormField widget2 = PdfFormField.CreateEmpty(stamper.Writer);
widget2.SetWidget(ssRectangle2, PdfAnnotation.HIGHLIGHT_TOGGLE);
tField.AddKid(widget1);
tField.AddKid(widget2);
stamper.FormFlattening = false;
stamper.AddAnnotation(tField, ssPage);
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();
}
(As I don't have that RCRectangleRecord, I use the iTextSharp Rectangle class as argument.)
This gives you two field visualizations in Adobe Acrobat Reader; after editing one of them and switching focus (e.g. clicking somewhere outside that visualization), the other visualization duplicates the content.
Now i have this and i can create two fields when the list has more than one Rectangle but for some reason i dont know how the two fields appears without the name!!
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
TextField tField;
if (ssRectangle.Count==1){
tField= new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle[0].ssSTRectangle.ssllx, (float)ssRectangle[0].ssSTRectangle.sslly, (float)ssRectangle[0].ssSTRectangle.ssurx, (float)ssRectangle[0].ssSTRectangle.ssury), ssName);
if (ssValue!="")
tField.Text = ssValue;
if (ssIsMultiline)
tField.Options = TextField.MULTILINE;
tField.FontSize = ssFontSize;
tField.FieldName = ssName;
stamper.AddAnnotation(tField.GetTextField(), ssPage);
}
else
{
PdfFormField PtField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 250);
PtField.Name=ssName;
foreach (RCRectangleRecord item in ssRectangle)
{
/*
tField=new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle[0].ssSTRectangle.ssllx, (float)ssRectangle[0].ssSTRectangle.sslly, (float)ssRectangle[0].ssSTRectangle.ssurx, (float)ssRectangle[0].ssSTRectangle.ssury), ssName);
tField.FieldName = ssName;
PtField.AddKid(tField.GetTextField());*/
PdfFormField widget = PdfFormField.CreateEmpty(stamper.Writer);
widget.SetWidget(new Rectangle((float)item.ssSTRectangle.ssllx, (float)item.ssSTRectangle.sslly, (float)item.ssSTRectangle.ssurx, (float)item.ssSTRectangle.ssury), PdfAnnotation.HIGHLIGHT_TOGGLE);
widget.Name = ssName;
PtField.AddKid(widget);
}
stamper.AddAnnotation(PtField, ssPage);
}
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();