how to place a table in pdf with a itext - javafx

public static void writeChartToPDF(int width, int height, String fileName) {
PdfWriter writer = null;
Document document = new Document();
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(
fileName));
document.open();
JFreeChart c= generateBarChart0();
PdfContentByte cb = writer.getDirectContent();
float wid = PageSize.A4.getWidth();
float heigh = PageSize.A4.getHeight() / 2;
PdfTemplate bar = cb.createTemplate(width, height);
Graphics2D g2d1 = new PdfGraphics2D(bar,width, height, new DefaultFontMapper());
Rectangle2D r2d1 = new Rectangle2D.Double(0, 0, width, height);
System.out.println("check 5");
c.draw(g2d1, r2d1);
g2d1.dispose();
cb.addTemplate(bar, 0, heigh);
PdfPTable table = new PdfPTable(3); // 3 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
document.close();
}
what am i missing here..? i want it to appear as table in the 1st followed by a bar chart. i have a nearly 5 charts and 5 table and i want it to appear in a new page. so each page has a table and a chart.

You're a developer, which means that you should be able to understand the answers that are given. For instance: when you asked jfreechart & itext for adding many number of barcharts, I answered that you can wrap a PdfTemplate inside an image:
Image img = Image.getInstance(bar);
document.add(img);
I'm not really happy that you didn't accept that answer, because it was a really good answer. I'm even less happy that you didn't follow that advice.
In a comment to your current question, I asked you to make a choice: either add the chart and the table at absolute positions, or use iText to do the layout. By wrapping the template inside an Image, adding that image with document.add() and then adding the table, you could solve your problem.
A solution that may even be more elegant would be to wrap the
for (PdfTemplate chart : charts) {
PdfPTable table = new PdfPTable(3); // 3 columns.
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell(Image.getInstance(chart), true);
cell.setColspan(3);
table.addCell(cell);
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.newPage();
}
In this example charts could be a list of PdfTemplate instances.

Related

Put Gridview into PDF template, iTextSharp

I'm attempting to use the code below to fill a PDF template with data from my webform. I want to know if it is possible to put a gridview into the form. Researching gives me mixed responses with some saying it can't be done and others that it can. I am not an experienced developer. Thanks in advance!
protected void btnPrint_Click(object sender, EventArgs e)
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headerCell in GridView2.HeaderRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(GridView2.HeaderStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(headerCell.Text, font));
pdfCell.BackgroundColor = new BaseColor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfCell);
}
foreach (GridViewRow gridViewRow in GridView2.Rows)
{
foreach (TableCell tableCell in gridViewRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(GridView2.RowStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
pdfCell.BackgroundColor = new BaseColor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfCell);
}
}
string fileNameExisting = Server.MapPath("~/Invoices/Invoice_Template.pdf");
string fileNameNew = Server.MapPath("~/Invoices/" + GridView1.SelectedRow.Cells[2].Text + "_Invoice.pdf");
PdfReader pdfReader = new PdfReader(fileNameExisting);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(fileNameNew, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("txtName", txtEmail.Text);
**pdfFormFields.SetField("table", pdfTable);**
string sTmp = "Invoice Generated for " + pdfFormFields.GetField("txtName");
MessageBox.Show(sTmp, "Finished");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}

Itextsharp refreshing page after creating PDF

I have a aspx page on which i have two buttons(MakePdf and View) on view button a gridview is shown on the page and with makePDF we can download PDF.
But what i need is view button code should be executing after downloading the PDF.
Please provide me a solution.
Document document = new Document(PageSize.A4, 0, 0, 15, 12);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
PdfPCell cell;
Phrase phrase;
PdfPTable table;
table = new PdfPTable(1);
table.SetWidths(new int[] { 10 });
table.SpacingBefore = 5f;
phrase = new Phrase();
phrase.Add(new Chunk("HSE Monthly Report ", TOPTextFont));
cell = new PdfPCell(new Phrase(phrase));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
table.AddCell(cell);
table.CompleteRow();
document.Add(table);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();

Odd Numbered Cell Not Added To Pdf

I am trying to add PdfPCell inside a loop to a iTextSharp Table with 2 columns in a Document. But if the count inside the loop is an odd number. Then the last cell does not get added. Can someone please provide a solution to this problem?
My code is below:
var doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~/QrCodes/") + fileName + ".pdf", FileMode.Create));
doc.Open();
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
foreach (var item in items)
{
if (itemImages.Any(p => p.Reference == item.Reference) == true)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(#item.ItemQrCode));
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, ImageFormat.Jpeg);
PdfPCell cellImage = new PdfPCell(pdfImage);
cellImage.HorizontalAlignment = Element.ALIGN_CENTER;
cellImage.VerticalAlignment = Element.ALIGN_MIDDLE;
cellImage.Border = 0;
table.AddCell(cellImage);
}
}
doc.Add(table);
doc.Close();
On your PdfPTable you can call the CompleteRow() method when you're done and missing cells will be filled in.

aspx to pdf using itextSharp 5.3.0

I am using this dll iTextSharp 5.3.0 to make a pdf file .
Is there a way to convert full .aspx page in pdf ? My page has grids and server side code .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
createPDF(Server.MapPath("Default.aspx"));
}
private void createPDF(string html)
{
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://test.pdf", FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
List<IElement> p = HTMLWorker.ParseToList(new StreamReader(html), new StyleSheet());
for (int k = 0; k < p.Count; k++)
{
document.Add((IElement)p[k]);
}
worker.EndDocument();
worker.Close();
document.Close();
}
It's working but the file test.pdf is just plain text. The html isn't well interpreted, my grids are missing and my server side values (the values from the grids) are also missing .
I also tried the codes from here:
http://forums.asp.net/t/1199774.aspx
and here:
Problem with HTMLParser in Itextsharp
Thanks in advance!
This is my honest advice! Don't waste your time on the HTMLWorker.ParseToList. It has a very elementary HTML parser.
Try this packge and you will never look back!
https://github.com/pruiz/WkHtmlToXSharp
ITextSharp only renders inline css, it is giving problem while adding CSS files.
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=BookingDetails.pdf");
System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.CreateBookingMainDiv.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(new Rectangle(922,1296),7f,7f,7f,0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
//HtmlPipeline
CssAppliers ca = new CssAppliersImpl();
//ICssFile cfile = new CssFileProcessor();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(ca);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//CSS stuff
//var cssResolver = new StyleAttrCSSResolver();
//var DamcoCss = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/damco.css"), FileMode.Open));
ICssFile cfile = new CssFileImpl();
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
//String DamcoCss = HttpContext.Current.Server.MapPath("~/css/damco.css");
//String BootStrapCss = HttpContext.Current.Server.MapPath("~/css/bootstrap.css");
//String BootStrapCssTheme = HttpContext.Current.Server.MapPath("~/css/bootstrap-theme.css");
//Add the external CSS file
//cssResolver.AddCssFile(DamcoCss, true);
//cssResolver.AddCssFile(BootStrapCss, true);
//cssResolver.AddCssFile(BootStrapCssTheme, true);
//Pipeline
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer)));
//XMLWorker
XMLWorker worker = new XMLWorker(pipeline, true);
//and...we parse
XMLParser parser = new XMLParser(true, worker);
//parser.AddListener(worker);
parser.Parse(sr);
parser.Flush();
pdfDoc.Close();
System.Web.HttpContext.Current.Response.Write(pdfDoc);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
//System.Web.HttpContext.Current.Response.End();
Use XMLWorker instead of HTMLWorker. works like charm.

iTextSharp appending table to document in memory stream after PDFStamper has been used

Hi I am trying to add a table to a pdf after I have used the stamper.
// CREATE MEMORY STRING
MemoryStream ms = new MemoryStream();
string formFile = Server.MapPath("testImg.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper outStamper = new PdfStamper(reader, ms);
AcroFields fields = outStamper.AcroFields;
// UPDATE THE FORM FIELDS
fields.SetField("Text1", "John Smith");
fields.SetField("Text2", "1234567890");
fields.SetField("Text3", "1234567890");
//ADD LOGO
iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
headerlogo.ScaleToFit(140, 399);
headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
headerlogo.SetAbsolutePosition(200, 500);
int pageCount = reader.NumberOfPages;
PdfContentByte body = outStamper.GetOverContent(pageCount);
body.AddImage(headerlogo);
outStamper.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
I want to be able to append the document with a table.
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.BorderWidth = 5;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
document.Add(table);
I am having trouble with defining the document to add the table to. Please can someone advise how I would add the table to the PDF in the Memory Stream.
Any help would be greatly appreciated.
Alex
Not sure how you have the two pieces working together but here is how I've done it for my application.
Basically i keep the stamping separate from adding structured content and then merging the results into one big pdf. You could try and do all of it together in one big step using table.WriteSelectedRows (which takes a PdfContentByte as one of its arguments) but the time that i have to spend with manual layouts, tends to outweigh the benefit of having it all done in one step (besides the fact that it becomes one huge method which is hard to maintain / reuse)
For clarification & testing purpose, I've used FileStream but of course, the same works fine with MemoryStream and reuse streams should you end up creating one monolithic function in your development code.
Here is my test application that I used to confirm the code and run your scenario:
Steps:
Create Test2.pdf (stamped contents
of original source) from Test.pdf
(our original source)
Create Test3.pdf (containing all our content to be appended at the end)
Open Test2.pdf & Test3.pdf and merge them into Test4.pdf final stream
Note: I haven't used image stamping code and you may have to adjust using on Document in first section if PdfStamper closes the underlying Document as well (can't recall if it does from top of my head but it will throw a helpful exception in case you need to adjust the using statement)
private static void Main(string[] args)
{
using (FileStream ms = new FileStream("C:\\Test2.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
//PdfStamper outStamper = new PdfStamper(reader, ms);
//PdfContentByte body = outStamper.GetOverContent(reader.NumberOfPages);
//document.Open(); //Open document to work with
//AcroFields fields = outStamper.AcroFields;
//// UPDATE THE FORM FIELDS
//fields.SetField("Text1", "John Smith");
//fields.SetField("Text2", "1234567890");
//fields.SetField("Text3", "1234567890");
////ADD LOGO
//iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
//headerlogo.ScaleToFit(140, 399);
//headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
//headerlogo.SetAbsolutePosition(200, 500);
//body.AddImage(headerlogo);
//outStamper.Close();
}
}
using (FileStream ms = new FileStream("C:\\Test3.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test2.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms);
document.Open();
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns")) { Colspan = 3, BorderWidth = 5, HorizontalAlignment = 1 };
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
table.CompleteRow(); //Added - table won't add the final row if its cells are incomplete - safe to have it ending a table
document.Add(table);
}
}
using (FileStream ms = new FileStream("C:\\Test4.pdf", FileMode.Create))
using (FileStream stampedfile = new FileStream("C:\\Test2.pdf", FileMode.Open))
using (FileStream appendfile = new FileStream("C:\\Test3.pdf", FileMode.Open))
{
PdfReader stampedContentReader = new PdfReader(stampedfile);
PdfReader appendContentReader = new PdfReader(appendfile);
using (Document document = new Document(stampedContentReader.GetPageSizeWithRotation(1)))
{
PdfCopy pdfCopy = new PdfCopy(document, ms);
document.Open();
for (int i = 1; i <= stampedContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(stampedContentReader, i));
for (int i = 1; i <= appendContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(appendContentReader, i));
}
}
}
Hope this helps.

Resources