How to get file size of multiple file download - asp.net

I am writing an ASP.NET web application.
I calculate the total size of my PDF file which is mentioned below. What does this return? When I download a 2KB file, it returns a size of 2KB, which is correct. But when I download 2 files each of size 2KB, then the total size it returns is 2.16KB. Is that correct? Should it return 4KB?
StringReader reader = new StringReader(content);
MemoryStream ms = new MemoryStream();
Document doc = new Document(PageSize.A4, 50, 50, 30, 30);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, ms);
doc.Open();
try
{
parser.Parse(reader);
}
catch (Exception ex)
{
Paragraph paragraph = new Paragraph("Error! " + ex.Message);
paragraph.SetAlignment("center");
Chunk text = paragraph.Chunks[0] as Chunk;
if (text != null)
{
//text.Font.Color = iTextSharp.text.BaseColor.RED;
}
doc.Add(paragraph);
}
finally
{
doc.SetMargins(10, 10, 10, 10);
doc.Close();
}
Byte[] buffer = ms.GetBuffer();
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=FileName.pdf");
//Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}

Sounds like you're opening two files into the same buffer and expecting them to be appended one to the other. Instead, the second is replacing the first.
Try all this stand-alone in a simple C# program. If it doesn't work there, it clearly won't work in an ASP page. OTOH, if it does work there, but not in ASP, then its an ASP issue, not a problem with iTextSharp.
PS: I thought doc.close would close the stream used by PdfWriter as well. Looking at the code, it will by default (protected boolean closeStream = true; from the java source). Something might have called setCloseStream(false) somewhere along the line.
PPS: Stacking two PDFs into the same binary stream is Not A Good Idea. You need to write them out as separate attachments... at which point this whole issue is moot.

Related

How to write text on different page based on text of exiting pdf using itextsharp

How to write Text on different pages on exiting pdf which have more then 1 page.
For example 'Hitesh Second Page' I want to write this word on second page
'Hitesh Third Page' I want to write this word on Third page
Below code work only for pdf which have one page.
string fileName = "test.pdf";
string oldFile = System.Web.Hosting.HostingEnvironment.MapPath("~/AuthDoc/CoverPage.pdf");
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName);
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
string text = "";
cb.BeginText();
text = "Hitesh Third Page";
cb.ShowTextAligned(3, text,500,500, 0);
cb.EndText();
cb.BeginText();
text = "Hitesh Second Page";
cb.ShowTextAligned(2, text,500,500, 0);
cb.EndText();
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate( page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
byte[] bytes = System.IO.File.ReadAllBytes(newFile);
return bytes;
Thanks,
Hitesh
When using a Document / PdfWriter pair to create a document, you create the pages in their final order, i.e. you first create the first page, then the second, then the third, ...
In your code you appear to try to start by creating the third page and then continue by creating the second one. You'll have to sort the code accordingly.
As soon as you have sorted your code, you can use the Document method NewPage to switch to the next page:
document.NewPage();
Beware, though, iText ignores the NewPage call if there is no content whatsoever on the page in question. To override this, you can make iText believe it is not empty using the PdfWriter property PageEmpty before calling NewPage:
writer.PageEmpty = false;
document.NewPage();
That been said, though...
How to write Text on different pages on exiting pdf
For such a task you should not use a Document / PdfWriter pair to start with, use a PdfReader / PdfStamper pair! In a PdfStamper you can quite freely jump between pages...

Present a PDF Document on a Specific Page in ASP.NET

I am opening PDF documents using the following ASP.NET code,
Response.BufferOutput = true;
Response.Clear();
Response.ContentType = "application/pdf";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(documentURL);
using (HttpWebResponse responseDDRINT = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = responseDDRINT.GetResponseStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, bufferSize)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
Response.Flush();
}
}
My question is does anyone know how to present the PDF starting at a specifice page. For example, if the PDF document is 15 pages, we would like it to open with page 10 initially showing instead of opening at page 1.
I experimented with the "#page=" open parameter by adding this header, but it did nothing.
Response.AddHeader("content-disposition", "inline; filename=test.pdf#page=3");
You'll have to manipulate the PDF file on the fly.
Use something like http://pdfsharp.com/PDFsharp/ to stream out a copy of the file starting at a certain page.
Current versions of Adobe ready no longer support the page syntax, but they do support the bookmark syntax.
Why don't you make your document reachable through a regular link or through an HTTPHandler?
you may use a PDF manipulation library like ItextSharp to get your work done.

How to create a pdf using webservice

I am using jquery ajax to call function from webservice.
In that function I am creating a pdf file using itextsharp tool.
I want that my pdf file created should open in browser when return.
can anyone help me what should be my return type for that
Below is the code I am using in webservice
public void GeneratePDf(string ID) {
string attachment = "attachment; filename=" + ID + ".pdf";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "12px");
htextw.AddStyleAttribute("color", "Black");
Page pg = new Page();
HtmlForm frm = new HtmlForm();
pg.EnableEventValidation = false;
pg.RenderControl(htextw);
Document document = new Document();
document = new Document(PageSize.A4, 10, 10, 0, 0);
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
document.Open();
Font verdana = FontFactory.GetFont("Verdana", 10, Font.BOLD, new CMYKColor(75, 68, 67, 90));
PdfPCell blank1 = new PdfPCell(new Phrase("Hello ", verdana));
document.Add(blank1);
//document.Add(tablegrid);
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
HttpContext.Current.Response.Write(document);
}
Can anyone tell me what I am doing wrong
The short answer is, "don't use AJAX for this", you are creating unnecessary complication. Instead, just make a normal GET/POST request via your browser. You can still use JavaScript if you want but the important part is that you have the browser make the request so that it can receive the response.
The long answer is...
Web servers respond to requests from web browsers and things happen just as you expect them to (usually). Web browsers have a list of content types that they are aware and use this list to sometimes parse the server's response and sometimes hand it off to a 3rd party application. Once you start messing around with AJAX and other similar technologies you break this model and are saying that you want to handle the processing instead of the browser. The browser will broker your request and the server's response but otherwise it won't do anything unless you tell it to. This works great for string-like things but gets much more complicated when you deal with binary data.

The document has no pages

I am using the below code to export gridview to PDF
form1.Controls.Clear();
form1.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
string html = "<html><body>" + sw.ToString() + "</body></html>";
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.AddAuthor("Ram");
document.AddSubject("Export To pdf");
document.Open();
string tempFile = Path.GetTempFileName();
using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
{
tempwriter.Write(html);
}
HtmlParser.Parse(document, tempFile);
document.Close();
writer.Close();
File.Delete(tempFile);
writer = null;
document = null;
Response.End();
I have checked that grridview has 10 rows by putting breakpoint. But I am getting error at
document.Close();
that
The document has no pages.
Any suggestion how to fix it?
1) Setting a breakpoint to see that your grid view has 10 rows helps, but only checks part of the problem. You also need to check the contents of tempFile. That's what iText is actually working with. If it's empty, you'll sill get the "doc has no pages" exception.
2.1) HtmlParser no longer exists within iText. Having said that, I just dug up this code sample via google:
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("html1.pdf"));
HtmlParser.parse(document, "example.html");
}
No opens or closes, just a call to HtmlParser. It's quite possible that HtmlParser checks to see if the document is already open, and won't proceed if it is... that would explain the behavior you're seeing.
2.2) The "correct" way to convert HTML these days goes something like this:
String html = readHtml();
List<Element> objects = HTMLWorker.parseToList(new StringReader(html), null);
for (Element element : objects)
document.add(element);
I had same issue and the below suggestion help and my issue is solved
Document has no pages means your GridView data is lost when you export.
Hence in the Export button event rebind the GridView with data from database
https://www.aspforums.net/Threads/264988/Export-GridView-to-PDF-Error-Document-has-no-pages/

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

Resources