Download multiple pdf documents using itextsharp - c#

i have a tree view in which there are certain set of document list and another grid having patient details. what i need to do is when we select docs from treeview (select multiple..checkbox enabled) and patients from grid and click on a button should create all the documents using ITEXTSHARP.that is multiple documents are created. I tried it like this,
on button click
foreach( TreeNode node in TreeView1.Nodes)
{
if (node.ChildNodes.Count>0)
{
for(int i=0 ;i<(node.ChildNodes.Count);i++)
{
if (node.ChildNodes[i].Checked==true)
{
string nodevalue = node.ChildNodes[i].Value.ToString();
if (nodevalue=="3")
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = row.FindControl("CheckBox1") as CheckBox;
if (chk.Checked)
{
Label lbl_name = row.FindControl("Label1") as Label;
Label lbl_dob = row.FindControl("Label3") as Label;
pdf_abcd(lbl_name.Text.Trim(), lbl_dob.Text.Trim());
}
}
}
}
}
}
}
}
}
}
and the pdf_abcd function is
public void pdf_abcd(string name, string dob)
{
Phrase hospt_name = new Phrase();
Phrase slogan = new Phrase();
Phrase address = new Phrase();
Phrase pat_name = new Phrase();
Phrase phr_Consent_For_Treatment = new Phrase();
Phrase phr_Professional_Care = new Phrase();
Phrase phr_Consent_For_Treatment_head = new Phrase();
Phrase phr_Professional_Care_head = new Phrase();
Phrase phr_Nursing_Care = new Phrase();
Phrase phr_Nursing_Care_head = new Phrase();
Phrase phr_signtur_line = new Phrase();
Phrase phr_signtur_bigfont = new Phrase();
Phrase phr_signtur_smallfont_line = new Phrase();
Phrase phr_signtur_date_line = new Phrase();
Phrase phr_relationship = new Phrase();
Phrase phr_witness = new Phrase();
Phrase phr_paitient_name = new Phrase();
Phrase phr_paitient_dob = new Phrase();
Paragraph para = new Paragraph();
Paragraph pat_det = new Paragraph();
Paragraph Consent_For_Treatment = new Paragraph();
Paragraph Professional_Care = new Paragraph();
Paragraph Nursing_Care = new Paragraph();
Paragraph Consent_For_Treatment_head = new Paragraph();
Paragraph Professional_Care_head = new Paragraph();
Paragraph Nursing_Care_head = new Paragraph();
Paragraph signatur = new Paragraph();
Paragraph relationship = new Paragraph();
Paragraph witness = new Paragraph();
Paragraph paitient_name_dob = new Paragraph();
Font fntNormalText = FontFactory.GetFont(FontFactory.TIMES, 12, iTextSharp.text.Font.NORMAL);
Font fntBoldText = FontFactory.GetFont(FontFactory.TIMES, 12, Font.BOLD);
Font fntsmallText = FontFactory.GetFont(FontFactory.TIMES, 8, Font.NORMAL);
Font fntverysmallText = FontFactory.GetFont(FontFactory.TIMES, 6, Font.NORMAL);
Font fntBoldheadingText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD);
Font fntparaText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL);
hospt_name = new Phrase("abcd", fntBoldText);
slogan = new Phrase(System.Environment.NewLine + "Quality health care here at home", fntNormalText);
address = new Phrase(System.Environment.NewLine + "P.O. Box 677", fntsmallText);
para.Add(hospt_name);
para.Add(slogan);
para.Add(address);
phr_paitient_name = new Phrase(System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + name + " " + dob, fntNormalText);
pat_name = new Phrase(System.Environment.NewLine + "__________________________________________________________ _______________________________" + System.Environment.NewLine + "Patient's Name D.O.B.", fntsmallText);
pat_det.Add(phr_paitient_name);
pat_det.Add(pat_name);
phr_Consent_For_Treatment_head = new Phrase(System.Environment.NewLine + "Consent For Treatment", fntBoldheadingText);
Consent_For_Treatment_head.Add(phr_Consent_For_Treatment_head);
phr_Consent_For_Treatment = new Phrase("The undersigned consents to procedures and treatments which may be performed during this hospitalization or on an outpatient or emergency basis, including but not limited to anesthesia, laboratory procedures, medical or surgical treatments, x-ray examination, or other services rendered under the general and specific instructions of the physician, physician's assistant, nurse practitioner or Designee. In order to manage accidental exposure of a health care worker to blood or other bodily fluids, the undersigned further consents to such testing; including but not limited to AIDS, TB, Syphilis, and Hepatitis testing, as may be necessary for protection of the heath care worker.", fntparaText);
Consent_For_Treatment.Add(phr_Consent_For_Treatment);
phr_Professional_Care_head = new Phrase(System.Environment.NewLine + "Professional Care", fntBoldheadingText);
Professional_Care_head.Add(phr_Professional_Care_head);
phr_Professional_Care = new Phrase("The attending physician, usually selected by the patient except under unusual or emergency circumstances, is the professional who arranges for the patient's care and treatment Doctors of medicine, including anesthesia provider, pathologists, radiologists, emergency room physicians, osteopathy, podiatry, etc., are independent contractors and are not employees of Val Verde Regional Medical Center. You will receive a separate bill from the physician/anesthesia provider.", fntparaText);
Professional_Care.Add(phr_Professional_Care);
phr_Nursing_Care_head = new Phrase(System.Environment.NewLine + "Nursing Care", fntBoldheadingText);
Nursing_Care_head.Add(phr_Nursing_Care_head);
phr_Nursing_Care = new Phrase("The hospital provides general nursing care. Private duty nursing must be arranged by the patient's representative. The hospital is not responsible for and is released from all liabilities for failure to provide such care.", fntparaText);
Nursing_Care.Add(phr_Nursing_Care);
phr_signtur_line = new Phrase(System.Environment.NewLine + System.Environment.NewLine + "__________________________________________________________________________________________ ________________", fntsmallText);
phr_signtur_bigfont = new Phrase(System.Environment.NewLine + "Signature of Patient/Responsible Party/Patient Representative", fntNormalText);
phr_signtur_smallfont_line = new Phrase("(If patient unable to sign)", fntverysmallText);
phr_signtur_date_line = new Phrase(" Date ", fntNormalText);
signatur.Add(phr_signtur_line);
signatur.Add(phr_signtur_bigfont);
signatur.Add(phr_signtur_smallfont_line);
signatur.Add(phr_signtur_date_line);
phr_relationship = new Phrase(System.Environment.NewLine + "______________________________________________________________" + System.Environment.NewLine + "Relationship to patient", fntNormalText);
relationship.Add(phr_relationship);
phr_witness = new Phrase(System.Environment.NewLine + "___________________________________ __________" + System.Environment.NewLine + "Signature of Witness Date", fntNormalText);
witness.Add(phr_witness);
Document Doc = new Document(PageSize.A4, 0, 0, 25, 50);
PdfWriter.GetInstance(Doc, new FileStream(Server.MapPath("~/abcd/abcd.pdf"), FileMode.Create));
Doc.Open();
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 500f;
table.LockedWidth = true;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("~/img/abcd.png");
logo.ScaleAbsolute(30, 30);
PdfPCell image_header = new PdfPCell(logo);
image_header.HorizontalAlignment = Element.ALIGN_CENTER;
image_header.BorderWidth = 0;
table.AddCell(image_header);
PdfPCell header = new PdfPCell(para);
header.HorizontalAlignment = Element.ALIGN_CENTER;
header.Colspan = 4;
header.BorderWidth = 0;
table.AddCell(header);
PdfPCell patient = new PdfPCell(pat_det);
patient.BorderWidth = 0;
table.AddCell(patient);
//PdfPCell patientname = new PdfPCell(new Phrase(System.Environment.NewLine + System.Environment.NewLine + "Patient's Name D.O.B."));
//patientname.BorderWidth = 0;
//table.AddCell(patientname);
PdfPCell head_treatment = new PdfPCell(new Phrase(Consent_For_Treatment_head));
head_treatment.BorderWidth = 0;
table.AddCell(head_treatment);
PdfPCell treatment_content = new PdfPCell(Consent_For_Treatment);
treatment_content.BorderWidth = 0;
table.AddCell(treatment_content);
PdfPCell head_profcare = new PdfPCell(Professional_Care_head);
head_profcare.BorderWidth = 0;
table.AddCell(head_profcare);
PdfPCell profcare_content = new PdfPCell(Professional_Care);
profcare_content.BorderWidth = 0;
table.AddCell(profcare_content);
PdfPCell head_nursing = new PdfPCell(Nursing_Care_head);
head_nursing.BorderWidth = 0;
table.AddCell(head_nursing);
PdfPCell nursing_content = new PdfPCell(Nursing_Care);
nursing_content.BorderWidth = 0;
table.AddCell(nursing_content);
PdfPCell sig = new PdfPCell(signatur);
sig.BorderWidth = 0;
table.AddCell(sig);
PdfPCell raltntopatient = new PdfPCell(relationship);
raltntopatient.BorderWidth = 0;
table.AddCell(raltntopatient);
PdfPCell witnesslines = new PdfPCell(witness);
witnesslines.BorderWidth = 0;
table.AddCell(witnesslines);
Doc.Add(table);
Doc.Close();
string path = Server.MapPath("~/abcd/Dabcd.pdf");
ShowPdf(path);
//Response.Redirect(Server.MapPath("~/abcd/abcd.pdf"));
}
and
private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
Response.Flush();
Response.Clear();
}
but the system only down loads one doc..can anyone helpme

If you step back and ignore PDFs for a bit and concentrate on just HTTP requests and responses you should have your answer. When a browser makes an HTTP request (your button click) the server is allowed to send one and only one response. You're code is trying (unsuccessfully) to send multiple responses to the browser. The first time that Response.End is called the pipeline gets terminated actually and the rest of your code doesn't run.
The solution is to just make one giant PDF in one pass, make individual PDFs and merge them or create a zip file containing all of the PDFs.

I guess you should create a zip file that combines your PDF files

If you want to Open the file in new tab you have different Methods:
Method 1:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
Method 2:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
Hope this helps you!

Related

Merge all the PDFs that been generated

I am developing a web application and one of its features is to generate a multiple certificate in a PDF file. There's no problem in generating a pdf but what I want to happen when generating a multiple certificate is to be in one pdf file only. I am just a beginner so I don't have much idea on doing that. Below is my code for generating a certificate. Thanks in advance!
protected void btnPdf_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString("MM-dd-yyyy");
foreach (GridViewRow row in TraineeGrid.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
Label varName = (Label)row.FindControl("lbName");
string name = varName.Text;
Label varCourse = (Label)row.FindControl("lbCourse");
string course = varCourse.Text;
Label varCertNum = (Label)row.FindControl("lbCertNum");
string certNumber = varCertNum.Text;
Label varEndDate = (Label)row.FindControl("lbEndDate");
string endDate = varEndDate.Text;
DateTime date = DateTime.Parse(endDate);
string finalEDate = date.ToString("MMMM dd, yyyy");
Label varStartDate = (Label)row.FindControl("lbStartDate");
string startDate = varStartDate.Text;
DateTime date1 = DateTime.Parse(startDate);
string dateFileName = date1.ToString("MM-dd-yyyy");
string finalSDate = date1.ToString("MMMM dd, yyyy");
var checkedBoxes = TraineeGrid.Controls.OfType<CheckBox>().Count(c => chk.Checked);
try
{
Directory.CreateDirectory("D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\");
string inputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\CertificateLayout.pdf";
string outputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\"+name+"_" + course + "_"+dateFileName+".pdf";
// open the reader
PdfReader reader = new PdfReader(inputCertificate);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document();
// open the writer
FileStream fs = new FileStream(outputCertificate, FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, fs);
PdfContentByte cb = stamp.GetOverContent(1);
var pageSize = reader.GetPageSize(1);
ColumnText ct = new ColumnText(cb);
PdfCopy copy = new PdfCopy(document, fs);
document.Open();
Font font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 45, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 600f, 325f);
Paragraph certText = new Paragraph(new Phrase(20, name, font));
ct.AddElement(certText);
ct.Go();
Font font2 = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 19, iTextSharp.text.Color.GRAY);
ct.SetSimpleColumn(10f, 100f, 600f, 390f);
certText = new Paragraph(new Phrase("This is to certify that ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 297f);
certText = new Paragraph(new Phrase("has successfully completed the " + course + " at BASS Philippines RHQ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 240f);
certText = new Paragraph(new Phrase("From: " + finalSDate + "", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 216f);
certText = new Paragraph(new Phrase("To: " + finalEDate + "", font2));
ct.AddElement(certText);
ct.Go();
Font font3 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 500f, 192f);
certText = new Paragraph(new Phrase("Certificate Number: " + certNumber + "", font2));
ct.AddElement(certText);
ct.Go();
stamp.Close();
reader.Close();
fs.Close();
Process.Start(outputCertificate);
chk.Checked = false;
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: "+ ex.Message.ToString() +" \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
}
}

How to introduce superscript in iTextSharp?

I want the output format date like 14th may 2015. the th in 14 it should come with sup tag but sup tag is not accessing here. the output i am getting in ph102 variable. Getsuffix(csq.EventDate.Value.Day) in this only i am getting suffix of th st and rd for date
My code:
PdfPTable table9 = new PdfPTable(4);
table9.WidthPercentage = 99;
table9.DefaultCell.Border = 0;
table9.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Phrase ph101 = new Phrase("Event Date & Time", textFont2);
PdfPCell cellt1 = new PdfPCell(ph101);
cellt1.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt1.PaddingTop = 0F;
cellt1.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt1.HorizontalAlignment = Element.ALIGN_LEFT;
DateTime eventTime = DateTime.Today;
if (!string.IsNullOrEmpty(Convert.ToString(csq.EventTime)))
eventTime = DateTime.Today.Add(csq.EventTime.Value);
Phrase ph102;
if (!string.IsNullOrEmpty(csq.EventDate.ToString()))
{
ph102 = new Phrase(csq.EventDate.Value.Day + Getsuffix(csq.EventDate.Value.Day) + csq.EventDate.Value.ToString("MMM") + " " + csq.EventDate.Value.Year + " at " + eventTime.ToString("hh:mm tt"), textFont7);
}
else
{
ph102 = new Phrase();
}
PdfPCell cellt2 = new PdfPCell(ph102);
cellt2.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt2.PaddingTop = 0F;
cellt2.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt2.HorizontalAlignment = Element.ALIGN_LEFT;
When I read your question, I assume that you want something like this:
However, you are confusing people as is demonstrated in the comment from somebody who gives you a hint to use HTML to PDF. Your answer is "no sir it cant work" which is a strange answer, because it can work. It's just not what you meant when you talked about sup tag. At least, that's what I assume when I look at your code, I don't see any HTML.
In your code, you create a Phrase like this:
ph102 = new Phrase(csq.EventDate.Value.Day
+ Getsuffix(csq.EventDate.Value.Day)
+ csq.EventDate.Value.ToString("MMM")
+ " " + csq.EventDate.Value.Year
+ " at " + eventTime.ToString("hh:mm tt"), textFont7);
This complete Phrase is expressed in textFont7 which can't work in your case, because you want to use a smaller font for the "st", "nd", "rd" or "th".
You need to do something like this (see OrdinalNumbers for the full example):
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Font small = new Font(FontFamily.HELVETICA, 6);
Chunk st = new Chunk("st", small);
st.setTextRise(7);
Chunk nd = new Chunk("nd", small);
nd.setTextRise(7);
Chunk rd = new Chunk("rd", small);
rd.setTextRise(7);
Chunk th = new Chunk("th", small);
th.setTextRise(7);
Paragraph first = new Paragraph();
first.add("The 1");
first.add(st);
first.add(" of May");
document.add(first);
Paragraph second = new Paragraph();
second.add("The 2");
second.add(nd);
second.add(" and the 3");
second.add(rd);
second.add(" of June");
document.add(second);
Paragraph fourth = new Paragraph();
fourth.add("The 4");
fourth.add(rd);
fourth.add(" of July");
document.add(fourth);
document.close();
}
This is the Java code to create the PDF in the screen shot. You'll have to adapt your code so that it works in C#. As you can see, you can not just concatenate your strings using the + operator. You need to compose your Phrase or Paragraph using different Chunk objects. What you call "sup" is done by using a smaller font and a text rise.

Why is my table not being generated on my PDF file using iTextSharp?

I'm trying to add a table to the PDF file I'm generating. I can add stuff "directly" but want to put the various paragraphs or phrases in table cells to get everything to align nicely.
The following code should add three paragraphs "free-form" first, then the same three in a table. However, only the first three display - the table is nowhere to be seen. Here's the code:
try
{
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
var titleFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
var docTitle = new Paragraph("UCSC Direct - Direct Payment Form", titleFont);
doc.Add(docTitle);
var subtitleFont = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
var subTitle = new Paragraph("(not to be used for reimbursement of services)", subtitleFont);
doc.Add(subTitle);
var importantNoticeFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", importantNoticeFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
importantNotice.ExtraParagraphSpace = 4; // ? test this....
doc.Add(importantNotice);
// Add a table
PdfPTable table = new PdfPTable(10); // the arg is the number of columns
// Row 1
PdfPCell cell = new PdfPCell(docTitle);
cell.Colspan = 3;
cell.BorderWidth = 0;
//cell.BorderColor = BaseColor.WHITE; <= this works for me, but if background is something other than white, it wouldn't
cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
// Row 2
PdfPCell cellCaveat = new PdfPCell(subTitle);
cellCaveat.Colspan = 2;
cellCaveat.BorderWidth = 0;
table.AddCell(cellCaveat);
// Row 3
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.Colspan = 5;
cellImportantNote.BorderWidth = 0;
table.AddCell(importantNotice);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
}
catch (DocumentException dex)
{
throw (dex);
}
catch (IOException ioex)
{
throw (ioex);
}
catch (Exception ex)
{
String exMsg = ex.Message;
MessageBox.Show(String.Format("Boo-boo!: {0}", ex.Message));
}
Why is my borderless table invisible or nonexistant?
UPDATE
Based on Bruno's answer, and applying it to the output that I really need, this works:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25)) {
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
// Mimic the appearance of Direct_Payment.pdf
var courierBold11Font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
var docTitle = new Paragraph("UCSC - Direct Payment Form", courierBold11Font);
doc.Add(docTitle);
var timesRoman9Font = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
var subTitle = new Paragraph("(not to be used for reimbursement of services)", timesRoman9Font);
doc.Add(subTitle);
var courier9RedFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", courier9RedFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
// Add a table
PdfPTable table = new PdfPTable(1);
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.BorderWidth = PdfPCell.NO_BORDER;
table.WidthPercentage = 50;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cellImportantNote);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
Please take a look at the SimpleTable7 example and compare the Java code with your [?] code:
This part is relevant:
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(cellImportantNote);
If I would convert your [?] code to Java, you'd have:
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(importantNotice);
Do you see the difference? You create a cellImportantNote instance, but you aren't using it anywhere. Instead of adding cellImportantNote to the table, you add the importantNotice paragraph.
This means that you are creating a table with 10 columns that has a single row of which only 6 cells are taken (because you have 1 cell with colspan 3, 1 cell with colspan 2 and 1 cell with colspan 1).
By default, iText doesn't render any rows that aren't complete, and since your table doesn't have any complete row, the table isn't being rendered.
If you look at the resulting PDF, simple_table7.pdf, you'll notice that I also added a second table. This table has only three columns, but it looks identical to the table you constructed. Instead of improper use of the colspan functionality, I defined relative widths for the three columns:
table = new PdfPTable(3);
table.setWidths(new int[]{3, 2, 5});
cell.setColspan(1);
table.addCell(cell);
cellCaveat.setColspan(1);
table.addCell(cellCaveat);
cellImportantNote.setColspan(1);
table.addCell(cellImportantNote);
document.add(table);
Note that I also avoid to use meaningless numbers. For instance, instead of:
cell.setHorizontalAlignment(0); // 0 means left
I use:
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
This way, people can read what this line means without having to depend on comments.
Furtermore, I replaced:
cell.setBorderWidth(0);
with:
cell.setBorder(PdfPCell.NO_BORDER);
That too, is only a matter of taste, but I think it's important if you want to keep your code maintainable.

Adding a new page using iTextSharp

I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)

label printer incorrectly prints itextsharp documents

the code below generate pdf documents:
using (FileStream fs = new FileStream("st.csv", FileMode.Open))
{
using (StreamReader configFile = new StreamReader(fs, System.Text.Encoding.GetEncoding("windows-1250")))
{
string line = string.Empty;
while ((line = configFile.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Replace("\"", "");
string[] varible = line.Split(';');
string number = varible[0];
string stName = varible[1];
string ewidenceNumber = varible[2];
string fileName = "barcodes\\" + Encryption.RandomString(10, true) + ".png";
Generate(line, fileName);
PdfPTable Table = new PdfPTable(2);
Table.WidthPercentage = 100;
Table.SetWidths(new[] { 110f, 190f });
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(fileName);
barcode.Border = 0;
barcode.ScalePercent(180f);
PdfPCell imageCell = new PdfPCell(barcode);
imageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(imageCell);
PdfPCell descriptionCell = new PdfPCell(new Paragraph(
"Enterprise 1 \n\n" +
number + "\n\n" +
"Number1: " + stName + "\n\n" +
"Number2: " + ewidenceNumber, _standardFont));
descriptionCell.HorizontalAlignment = Element.ALIGN_CENTER;
descriptionCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(descriptionCell);
Table.KeepTogether = true;
Table.SpacingAfter = 10f;
doc.Add(Table);
}
}
}
}
and here is the problem: vertical and horizontal view in adobe acrobat displays correctly, but when I need to print labels with this information CITIZEN label printer always prints it in horizontal view. I can't adapt this data to print in correct orientation. Anyone has solution for this problem? Maybe I incorrectly rotate cells in table?
I would suggest you drop PDF and instead write to it's native format: http://www.citizen-europe.com/support/progman.htm
PDF printing support is supplied by the driver. If the driver doesn't know how to interpret the specific PDF commands then it's not going to work. Usually label printers don't provide very good driver support for anything but writing to their native format or emulating ZPL (zebra) and Datamax.

Categories

Resources