I am generating the PDF using iTextSharp.i have a HTMl Page and i am Reading HTML Page then generate the PDF.but the Problem is that the half of the page is in PDF while another half of the Page is running out the page in PDF.i mean half of the Page is displayed in PDF.while half of the Page is cutting in PDF.
my code is like this in Load Event..
string fileContents;
string FilePath = Server.MapPath("print-withoutlogin.html");
StreamReader mstrFileStreamReader = new StreamReader(FilePath);
try
{
fileContents = mstrFileStreamReader.ReadToEnd();
byte[] result = createPDF(fileContents.ToString()).GetBuffer();
Response.Clear();
Response.AddHeader("Content-Length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.AddHeader("Accept-Ranges", "bytes");
Response.Buffer = true;
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "public");
Response.AddHeader("content-Transfer-Encoding", "binary");
Response.AddHeader("Content-Disposition", "attachment; filename=kartik.pdf");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
mstrFileStreamReader.Close();
}
and
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 0, 0, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
HTMLWorker worker = new HTMLWorker(document);
//worker.SetStyleSheet(styles);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Have you Considered using Crystal Reports? I find it much easier and you can use
pdfStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Related
Converting Binary "data:image/jpeg;base64," to pdf but not getting correct output, my binary string is very long which content 10 pages of pdf, Image url i am getting full image, but when i am generation ToBase64String to pdf then only one page
string folderPath = Server.MapPath("~/ImageFiles/");
WebBrowser webrowse = sender as WebBrowser;
Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height, PixelFormat.Format16bppRgb565);
webrowse.DrawToBitmap(bitmap, webrowse.Bounds);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] strbytes = stream.ToArray();
imgscreenshot.Visible = true;
imgscreenshot.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(strbytes);
string base64 = Convert.ToBase64String(strbytes);
byte[] imageBytes = Convert.FromBase64String(base64);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
document.Add(image);
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
In below Image is single page generated and not in center position also and arround 10 pages should come but that is not generated
Here is my code and it works (I used NuGet package Select.HtmlToPdf. Document.Save saves the PDF instead I would like the PDF open for user to review (instead of saving in computer)
HtmlToPdf converter = new HtmlToPdf();
// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl("www.cnn.com");
// save pdf document
doc.Save.(Response, false, "test.pdf"); // false: will not save the document
// close pdf document
doc.Close();
To open in browser, after PDFDocument initiated:
PdfDocument doc = converter.ConvertHtmlString("www.cnn.com");
byte[] bytes = doc.Save();
string mimeType = "Application/pdf";
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();
I new in using ITextSharp and want create a simple pdf file. And I trying in localhost, it work fine but put in server it fail to create and show the error message " The document has no pages.". I got try find the solution in web but still the same. How to solve this kind of problem?
Below is my coding.
var html = GenerateHTML(lst, getuser);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Commision_" + name + "_" + DateTime.Now.ToString("yyyyMM") + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Render PlaceHolder to temporary stream
StringReader reader = new StringReader(html);
//Create PDF document
Document doc = new Document(PageSize.A4);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
try
{
doc.NewPage();
parser.Parse(reader);
}
catch (Exception )
{
}
finally
{
doc.Close();
}
I guess you missed the following 2 lines after doc.close
Response.Write(doc);
Response.End();
I'm trying to generate a pdf file using itextsharp.
Here is the method that's supposed to generate the PDF:
private void Page_onPreRenderComplete(object sender, EventArgs e)
{
// createPdf.GeneratePDF(htmlMarkup);
MemoryStream memoryStream = new MemoryStream();
StringBuilder sBuilder = new StringBuilder();
StringWriter sw = new StringWriter(sBuilder);
HtmlTextWriter htmlText = new HtmlTextWriter(sw);
Page.RenderControl(htmlText);
string pdfBody = sBuilder.ToString();
Document document = new Document();
PdfWriter.GetInstance(document, memoryStream);
document.Open();
StyleSheet styles = new StyleSheet();
HTMLWorker hw = new HTMLWorker(document);
try
{
hw.Parse(new StringReader(pdfBody));
}
catch (Exception ex)
{
string msg = ex.Message;
}
finally
{
document.Close();
}
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Write(memoryStream);
HttpContext.Current.Response.End();
}
an error is generated on the line within the try block. How can I fix this?
may be the image tags etc are in relative paths instead of absolute paths in the rendered HTML
I already generate a pdf using itextsharp..and save it in our local server. I want to download this pdf in another button click. Code for generate pdf is working properly.Downloading occured but some error ocuured trying to open it."Because it is either not a supportive file type,or file has been damaged
protected void createpdf_Click(object sender, EventArgs e)
{
fs = new FileStream(Server.MapPath("pdf") + "\\" + "First PDF document.pdf", FileMode.Create);
document = new Document(PageSize.A4, 25, 25, 30, 30);
writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.Add(new Paragraph("Pdf Geneartion!"));
document.Close();
writer.Close();
fs.Close();
}
Code for download pdf
protected void download_Click(object sender, EventArgs e)
{
try
{
fs = new FileStream(Server.MapPath("pdf") + "\\" + "FirstPDFdocument1.pdf", FileMode.Create);
document = new Document(PageSize.A4, 25, 25, 30, 30);
writer = PdfWriter.GetInstance(document, fs);
using (MemoryStream ms = new MemoryStream())
{
document.Open();
Response.Clear();
Response.ContentType = "pdf/application";
Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
writer.Close();
fs.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Everything looks more or less correct except the ContentType. It should be application/pdf instead of pdf/application. Also, as #lc points out, the MemoryStream does not look like it is being written to. Try something like this instead:
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms); // added
document.Open();
Response.Clear();
Response.ContentType = "application/pdf"; // changed
Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}