I am trying to export a div to pdf with style using code:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + Fullname.Text + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
var cssText = System.IO.File.ReadAllText(Server.MapPath("/css/bootstrap.css"));
var memoryStream = new MemoryStream();
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
pfd.RenderControl(htmlTextWriter);
StringReader stringReader = new StringReader(stringWriter.ToString().Replace("<br>", "<br/>").Replace("<td>", "<td/>").Replace("<tr>", "<tr/>").Replace("<td>", "<td/>"));
Document Doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, Doc, stringReader);
Doc.Close();
Response.Write(Doc);
Response.End();
How i can attach css file to pdf to keep same appearance in HTML?
Try below code,
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
byte[] pdf; // result will be here
var cssText = File.ReadAllText(MapPath("~/css/style.css"));
var html = File.ReadAllText(MapPath("~/css/index.html"));
using (var memoryStream = new MemoryStream())
{
var document = new Document(PageSize.A4, 20, 20, 30, 30);
var writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
}
}
document.Close();
pdf = memoryStream.ToArray();
}
Related
I'm calling ExportToPDF2 method in a for loop to produce pdf documents.
The problem is the loop stops after the Respons.End().
How can I get this resolved, and is there a better way than using this technique?
private int ExportToPDF2()
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
return 0;
}
It strange to me that you are saving the output of same page (Page.RenderControl(hw);) multiple times!
Anyway, It's not possible to send multiple outputStream from Server, you can try
Response.Write(somefile);
Response.End();
textBox1.Text = "1111"; // it wont work because you can't have multiple outputstream
The best workaround you can have is to make a zip file then do Response.Write(zipFile)
But if you still insist on having them separately(multiple downloads) better you save each file on the server first by:
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath("~") + pdfName + ".pdf");
}
then use this trick https://stackoverflow.com/a/30682695/336511 to support multiple download. note that this will work on modern browsers.
var links = [
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'
];
function downloadAll(urls) {
var link = document.createElement('a');
link.setAttribute('download', null);
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
<button onclick="downloadAll(window.links)">Test me!</button>
My iTextSharp Code is like below I am using XSLT for getting HTML design:
int pageCount = GetNoofPages(outputString);
StringReader sr = new StringReader(outputString.Replace("###Noofpages###", pageCount.ToString()));
byte[] content = null;
string savedfile = string.Empty;
using (MemoryStream myMemoryStream = new MemoryStream())
{
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 40f, 10f, 40f, 36);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
StyleSheet style = new StyleSheet();
htmlparser.SetStyleSheet(style);
PdfWriter myPDFWriter = PdfWriter.GetInstance(pdfDoc, myMemoryStream);
pdfDoc.Open();
htmlparser.Parse(sr);
HTMLWorker htmlparser1 = new HTMLWorker(pdfDoc);
StyleSheet style1 = new StyleSheet();
htmlparser1.SetStyleSheet(style1);
pdfDoc.Close();
content = AddPageNumbers(myMemoryStream.ToArray());
}
return content;
My output is:
Leg 1: 4311 route
// Now rest of the page is blank
.
.
.
.
.
// Now it will continue on next page
Route details:
// remaining instructions
Please help me.
my code is:
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
GridView2.AllowPaging = false;
GridView2.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new iTextSharp.text.Document(PageSize.A2);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("contentdisposition","attachment;filename=CustomerReport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}*/
please help me to resolve this. In this i am getting font size too small error.Error in htmlparser.parse()
We are unable to change font size of pdf generated from below code anybody can help us?
We would like to convert that html file into pdf after changing the font size.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
protected void ConvertToPDFNow()
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
print.RenderControl(w);
string htmWrite = sw.GetStringBuilder().ToString();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>", "");
htmWrite = htmWrite.Replace("\r\n", "");
StringReader reader = new StringReader(htmWrite);
Document doc = new Document(PageSize.A4);
//Creating Document of A4 Size
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
try
{
//rendering Html File
parser.Parse(reader);
}
catch (Exception ex)
{
}
finally
{
doc.Close();
}
}
try to apply stylesheet:
...
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "12px");
parser.SetStyleSheet(style);
...
The C# code below works fantastically to change itextpdf font size:
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "8px");
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.SetStyleSheet(style);
How do one create PDF in memorystream instead of physical file using itextsharp.
The code below is creating actual pdf file.
Instead how can I create a byte[] and store it in the byte[] so that I can return it through a function
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
doc.Close(); //Close document
Switch the filestream with a memorystream.
MemoryStream memStream = new MemoryStream();
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
...
return memStream.ToArray();
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
byte[] pdfBytes;
using(var mem = new MemoryStream())
{
using(PdfWriter wri = PdfWriter.GetInstance(doc, mem))
{
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
}
pdfBytes = mem.ToArray();
}
I've never used iTextPDF before but it sounded interesting so I took upon the challenge and did some research on my own. Here's how to stream the PDF document via memory.
protected void Page_Load(object sender, EventArgs e)
{
ShowPdf(CreatePDF2());
}
private byte[] CreatePDF2()
{
Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
doc.Open();
Paragraph header = new Paragraph("My Document") {Alignment = Element.ALIGN_CENTER};
Paragraph paragraph = new Paragraph("Testing the iText pdf.");
Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here.");
Chunk chunk = new Chunk("This is a chunk.");
doc.Add(header);
doc.Add(paragraph);
doc.Add(phrase);
doc.Add(chunk);
doc.Close();
return output.ToArray();
}
}
private void ShowPdf(byte[] strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(strS);
Response.End();
Response.Flush();
Response.Clear();
}
Where your code has new FileStream, pass in a MemoryStream you've already created. (Don't just create it inline in the call to PdfWriter.GetInstance - you'll want to be able to refer to it later.)
Then call ToArray() on the MemoryStream when you've finished writing to it to get a byte[]:
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
// Write to document
// ...
return output.ToArray();
}
I haven't used iTextSharp, but I suspect some of these types implement IDisposable - in which case you should be creating them in using statements too.