CSV to PDF file in c# - c#

I am trying to convert a comma separated string(CSV) file to pdf file in C# using the iTextSharp library. I would like to know if there is any other free or more efficient tool/way for this type of conversion.

You can use iTextSharp
Here's an example:
Document pdfDoc = new Document();
string path = #"c:\file.pdf";
PdfWriter writer = PdfWriter.GetInstance( pdfDoc, new FileStream(path, FileMode.OpenOrCreate));
pdfDoc.Open();
pdfDoc.Add(new Paragraph("your data"));
pdfDoc.Close();

Related

How to use itext 7 to generate a PDF from an HTML div and save it to a folder on the server in .net

I'm trying to create a CV builder that saves the CV edited by the user to a folder in my project for further processing of sending it through email, I have reached as far as using itext to create a PDF of an HTML div, but has no CSS or any of the text values I have returned from my database. Through some research i find that my problem could be solved by using itext 7 and an add-on pdfHTML but can not find any proper examples of how to use it with my ASP.NET code. Would really appreciate any help.
Bellow is the code for the on-click button event I use to generate the PDF
protected void ButtonDownload_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
//Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
contentdiv.RenderControl(hw); //convert the div to PDF
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
string filename = base.Server.MapPath("~/PDF/" + "UserCV.pdf");
HttpContext.Current.Request.SaveAs(filename, false);
Response.End();
}
This picture shows the pdf result i get when i click the download button
And this is html page it is trying to convert
The text bellow the headings on the HTML page are Labels whose values are being set by retrieving values form a database
This is an example on how to use pdfHTML
This example is quite extensive, as it also sets document properties, and registers a custom Font.
public void createPdf(String src, String dest, String resources) throws IOException {
try {
FileOutputStream outputStream = new FileOutputStream(dest);
WriterProperties writerProperties = new WriterProperties();
//Add metadata
writerProperties.addXmpMetadata();
PdfWriter pdfWriter = new PdfWriter(outputStream, writerProperties);
PdfDocument pdfDoc = new PdfDocument(pdfWriter);
pdfDoc.getCatalog().setLang(new PdfString("en-US"));
//Set the document to be tagged
pdfDoc.setTagged();
pdfDoc.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
//Set meta tags
PdfDocumentInfo pdfMetaData = pdfDoc.getDocumentInfo();
pdfMetaData.setAuthor("Joris Schellekens");
pdfMetaData.addCreationDate();
pdfMetaData.getProducer();
pdfMetaData.setCreator("JS");
pdfMetaData.setKeywords("example, accessibility");
pdfMetaData.setSubject("PDF accessibility");
//Title is derived from html
// pdf conversion
ConverterProperties props = new ConverterProperties();
FontProvider fp = new FontProvider();
fp.addStandardPdfFonts();
fp.addDirectory(resources);//The noto-nashk font file (.ttf extension) is placed in the resources
props.setFontProvider(fp);
props.setBaseUri(resources);
//Setup custom tagworker factory for better tagging of headers
DefaultTagWorkerFactory tagWorkerFactory = new AccessibilityTagWorkerFactory();
props.setTagWorkerFactory(tagWorkerFactory);
HtmlConverter.convertToPdf(new FileInputStream(src), pdfDoc, props);
pdfDoc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The most relevant line here is
HtmlConverter.convertToPdf(new FileInputStream(src), pdfDoc, props);
Which essentially tells pdfHTML to perform the conversion of the inputstream (specified by src), put the content in pdfDoc and use the given ConverterProperties (specified by props).

How to store Generated pdf on deployed website with Itext

I am trying to write to a pdf and send it in an email.I am able to implement this on my local machine. The problem is when I deploy to azure I am not sure where to store the pdf . I have seen one question regarding this
and tried this solution from stackoverflow -
Does iText (any version) work on Windows Azure websites?.
var path = Server.MapPath("test.pdf");
FileInfo dest = new FileInfo(path);
var writer = new PdfWriter(dest);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("hello world"));
document.Close();
I get an error
Could not find a part of the path
'D:\home\site\wwwroot\Email\test.pdf'.
Try to create the Pdf in memory and stream the content to the asp.net output stream.
Document document = new Document(PageSize.A4);
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.NewPage();
...
...
document.Close();
Response.Clear();
Response.ContentType = "application/pdf";
byte[] pdfBytes = ms.ToArray();
Response.AppendHeader("Content-Length", pdfBytes.Length.ToString());
Response.OutputStream.Write(pdfBytes, 0, (int)pdfBytes.Length);
I suppose your issue is related with the file path.
If I use the path like Server.MapPath("Azure_Example1.pdf"), I also get the same error as you.
I suggest you could try to use the relative path like Server.MapPath("~/Azure_Example1.pdf"). The '~/' points to the project root directory.
You could also set a break point to check the value of path by using remote debugging.
I have created a simple demo, it works fine on my side. You could refer to.
Install the iTextSharp 5.5.13 nuget package in Manage Nuget Packages.
Use the following code:
var path = Server.MapPath("~/Azure_Example1.pdf");
FileInfo dest = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
doc.Add(new Paragraph("Hello World")); //change content in pdf
doc.Close();
Finally, you could see the pdf file has been stored in root project directory.

How to convert stringbuilder text and get pdf format file output in asp.net

I'm using Visual Studio 2008 and I need to convert some stringbulider text and get pdf format output file on button click event..
Following is sample stringbuilder text.
StringBuilder reqReport = new StringBuilder();
reqReport.Append("<li>Five copies of your latest Passport size.</li>");
reqReport.Append("<li>Your certificates, testimonials etc. (in original with one photocopy)</li>");
reqReport.Append("<li>Residence & Identity proof required in Bank account opening process as per RBI guidelines.</li>");
I tried using itextsharp..
string html = reqReport.ToString();
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(pdfDoc, _xmlr);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Table.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
This creates the pdf file.. But when I try to open the file, it shows the the file is either corrupted or damaged and could not be opened..
Is there any other format to do the function..?
Thanks in advance...

How to convert HTML into PDF using iTextSharp in winform?

I want to convert HTML into PDF in windows form. I have come across many fabulous articles online such as these:
http://www.aspsnippets.com/Categories/iTextSharp.aspx
http://www.aspsnippets.com/Articles/Export-HTML-DIV-contents-to-PDF-using-iTextSharp-in-ASPNet.aspx
http://www.aspsnippets.com/Articles/Export-ASP.Net-GridView-to-PDF-with-Custom-Columns-Widths-using-iTextSharp.aspx
But they do not quite address my problem.
Is it possible that I can just pass a string of HTML and convert it into PDF in Winform?
For example :
string html = "<table><tr><td>Arbaaz</td><tr></table>"
Can I just pass this string to some iText method to create PDF?
Got the answer I was looking for here ..
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();
https://stackoverflow.com/a/18378661/2064292

iTextSharp stops after 2 pages

I'm trying to convert HTML to PDF with iTextSharp.
Here's my code:
Document doc = new Document(PageSize.A4);
StringReader reader = new StringReader(responseHtml);
FileStream pdfStream = new FileStream("C:\\temp\\foo.pdf", FileMode.OpenOrCreate);
PdfWriter writer = PdfWriter.GetInstance(doc, pdfStream);
doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader);
doc.Close();
The issue is that the PDF file stops after 2 pages.
The rest of the content just doesn't make it to the PDF file.
When I change the PageSize to A1, I get the whole content, 'cause it fits on two A1 pages.
How do I get it to create more than two pages?

Categories