Sending a PDF document to an HTTPResponse object

Hi there,

I have been trawling your forums trying to do the reasonably simple task of sending a PDF file to an HTTP response object. This is really easy with Word and Cell where you just call Save(webcontext,filename, inline, null) (or something similar) but the documentation and examples for PDF Document (particularly for Save(Stream)) are minimal to the point of non-existent! For other people going forward, please can you add some concrete samples to your save methods for this simple task?
In the meantime, please can give me an example of how to send a PDF file back to the browser?
I am using the Aspose.PDF document not the pdf kit v6.0.0.0 as part of the Total edition in VS2010 & .Net4

Thanks
Jon

Hello Jon,

Thanks for your interest in our products.

When using Aspose.Pdf.Generator namespace of Aspose.Pdf for.NET, you may try using public void Save(string,SaveType,HttpResponse); method of Pdf class to display the resultant PDF in web browser. In cae you face any problem or you have any further query, please feel free to contact. We apologize for your inconveniecne.

[C#]

// Instantiate an object PDF class
Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
// add the section to PDF document sections collection
Aspose.Pdf.Generator.Section section = pdf.Sections.Add();
//Create text paragraphs
Aspose.Pdf.Generator.Text text2 = new Aspose.Pdf.Generator.Text(section, "Hello World...");
//Add the text paragraphs to the section
section.Paragraphs.Add(text2);
//Save the pdf document
pdf.Save("HelloWorld.pdf", Aspose.Pdf.Generator.SaveType.OpenInBrowser,Response);

Hi there,

Thanks for your reply. Just to give an example of what I am doing, I am rendering a variety of documents using your word and cell controls.

Items then get added to an object list (which may contain mixtures of PDF, Excel, and Word items) and then, if required, get rendered into a single PDF document. In the same process, they may be left in their original format and saved to the hard disk as Word or Excel files and, as part of the same process, may be sent back to the user’s browser as a single PDF or in their individual state if there is only one item.

For instance, if there is only one Word document, then it can be sent out using something like this:

Aspose.Words.Document docWord = ((Aspose.Words.Document)item);
docWord.Save(HttpContext.Response, renderFileName, Aspose.Words.ContentDisposition.Inline, null);

If there is more than one item, it will be combined automatically in a function.

returnDoc = new Aspose.Pdf.Document();
returnDoc.EmbeddedFiles.Add((Aspose.Pdf.FileSpecification)(GetRenderedElement(item)));

Where GetRenderedElement contains the following code:

Aspose.Words.Document tmpDoc = WorkingDoc;

// If an individual element needs to be PDF then render it to PDF before adding to
// the final output document. If the overall document needs to be rendered as
// PDF, these will just be added to the collection
MemoryStream saveDocMS = new MemoryStream();
tmpDoc.Save(saveDocMS, Aspose.Words.SaveFormat.Doc);
returnValue = new Aspose.Pdf.FileSpecification(saveDocMS, item.ElementName);

Given the capabilities of the PDF generator object, I am unsure of the best way to import these rendered PDF files. I tried the following but it just produces a blank document.

Aspose.Pdf.FileSpecification docPDF = ((Aspose.Pdf.FileSpecification)item);
MemoryStream saveDocPDF = new MemoryStream();
docPDF.Contents.CopyTo(saveDocPDF);

Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
Aspose.Pdf.Generator.DocumentAttachment att = new Aspose.Pdf.Generator.DocumentAttachment();
att.DocumentAttachmentCotentType = "application/pdf";
att.DocumentAttachmentStream = saveDocPDF;
pdf.DocumentAttachments.Add(att);
pdf.Save("XXXX.pdf", Aspose.Pdf.Generator.SaveType.OpenInAcrobat, HttpContext.Response);

Is there an obvious method call I am missing?

I would have expected the Generator to accept a PDF.FileSpecification as one of its overloads since that seems to be the only way to save a PDF document.

A better alternative would be that a PDF document (which does accept the file specification as an embedded file) has a save to web response method something like this:

Aspose.Pdf.Document x = new Aspose.Pdf.Document();
Aspose.Pdf.FileSpecification docPDF = ((Aspose.Pdf.FileSpecification)item);
x.EmbeddedFiles.Add(docPDF);
x.Save("XXXX.pdf", Aspose.Pdf.Generator.SaveType.OpenInAcrobat, HttpContext.Response);

Hopefully, this is not too confusing, but please can you suggest what I am doing wrong with this?

(BTW, DocumentAttachmentContentType is spelled wrong.)

Thanks

Jon :slight_smile:

Hello Jon,

We are working over this query and will get back to you soon. We are sorry for the delay and inconvenience.

Hi there,

Any progress with this (or at least a workaround (even if it is slightly convoluted for the minute))

thanks
Jon

Sorry to keep bugging you about this but is there an eta on when you expect to get time to look at this?


thanks

Jon

Hello Jon,

Sorry for the delay and replying you late. I hope to get back to you over this matter by today. Please be patient and spare us little time. We apologize for your inconvenience.

No worries. :slight_smile:

Hello Jon,

Thanks for your patience. As far as I have understood, in above code snippet you are trying to combine the features of two components i.e. passing Aspose.Words object as an argument to Aspose.Pdf method. In case you need to embed any file format into PDF document, please checkout the instructions specified over following links

  • Add Attachment In a PDF Document (In case you need to use Aspose.Pdf namespace)
  • Add Attachment from a File in an Existing PDF (Facades)

Given the capabilities of the PDF generator object, I am
unsure the best way to import these rendered PDF files. I tried the
following but it just produces a blank document.

In order to get the attachments present inside PDF document, please visit the following link for information on Response);

  • Get All the Attachments from a PDF Document
  • Extract All Attachments to Disk From Existing PDF File (Facades)

I would have expected the Generator to accept a
PDF.FileSpecification as one of it’s overloads since that seems to be the only
way to save a PDF document.

This requirement is not accomplished because Aspose.Pdf and Aspose.Pdf.Generator are two separate namespaces. However, as per my understanding, in case you have attached different file formats into PDF document and want to render the resultant PDF document over client side, you may checkout this demo to get an idea on how to render the resultant PDF to Response object.

A better alternative would be that a PDF document (which
does accept the file specification as an embedded file) has a save to web
response method

I have logged the requirement to introduce an new method in Document class which can accept Response object as an argument. It has been logged as PDFNEWNET-29779. We will further look into the details of this requirement and will keep you updated on the status of correction.

(BTW, DocumentAttachmentContentType is spelt wrong… )
Thanks for your notification. We hope to get it resolved shortly.

In case I have still not understood your requirement or you have any further query, please feel free to contact. We apologize for your inconvenience.

Hi there, managed to get it working in the end with a combination of PDF kit and old school html headers.. The ability to directly create a PDF document direct from a Aspose.Pdf.FileSpecification without having to pass it to and from streams would also be useful!

/// 
/// The rendered document list that can then be processed according to the final rendering instructions
///  
private Dictionary<string, object> renderedDocList = new Dictionary<string, object>();
........
 One change I missed was to make word save format.PDF
..........

Aspose.Words.Document tmpDoc = ((WordRenderer)docAsObject).WorkingDoc;
// If an individual element needs to be PDF then render it to PDF before adding to
// the final output document.  If the overall document needs to be rendered as 
// PDF, these will just be added to the collection
MemoryStream saveDocMS = new MemoryStream();
tmpDoc.Save(saveDocMS, Aspose.Words.SaveFormat.Pdf);
returnValue = new Aspose.Pdf.FileSpecification(saveDocMS, item.PageName);
........
playing around with memory streams adding all the items together using the (soon to be obsolete?) PDF.Kit
.........
case "Aspose.Pdf.FileSpecification":                        
    // https://forum.aspose.com/t/106387 
    anyHasPDF = true;
Aspose.Pdf.<span style="color:#2b91af;">FileSpecification</span> docPDF = ((Aspose.Pdf.<span style="color:#2b91af;">FileSpecification</span>)item);
<span style="color:#2b91af;">MemoryStream</span> saveDocPDF = <span style="color:blue;">new</span> <span style="color:#2b91af;">MemoryStream</span>();
docPDF.Contents.Position = 0;

<span style="color:green;">// Concatonate still only part of the PDF Kit</span>
docPDF.Contents.CopyTo(saveDocPDF);
saveDocPDF.Position = 0;
Aspose.Pdf.Kit.<span style="color:#2b91af;">PdfFileEditor</span> edt = <span style="color:blue;">new</span> Aspose.Pdf.Kit.<span style="color:#2b91af;">PdfFileEditor</span>();
edt.Concatenate(saveDocPDF, workingStream, outputStream);
             
<span style="color:blue;">break</span>;
Slight hack to get round lack of Save to response object in PDF Document
if (renderedDocList.Keys.Count > 0 || this.ForceAsPDF || anyHasPDF)
{
// create a byte array that will hold the output pdf
byte[] outBuf = outputStream.GetBuffer();
<span style="color:green;">// specify the duration of time before a page,cached on a browser expires</span>
WebContext.Response.Expires = 0;

<span style="color:green;">// Specify the property to buffer the output page</span>
WebContext.Response.Buffer = <span style="color:blue;">true</span>;

<span style="color:green;">// Erase any buffered HTML output</span>
WebContext.Response.ClearContent();
<span style="color:green;">//Add a new HTML header and value to the response sent to the client</span>
WebContext.Response.AddHeader(<span style="color:#a31515;">"content-disposition"</span>, <span style="color:#a31515;">"attachment; filename="</span> + <span style="color:#2b91af;">Path</span>.GetFileNameWithoutExtension(WorkingDocument.RenderFileName) + <span style="color:#a31515;">".pdf"</span>);
<span style="color:green;">// Specify the HTTP content type for response as Pdf</span>
WebContext.Response.ContentType = <span style="color:#a31515;">"application/pdf"</span>;
<span style="color:green;">// Write specified information of current HTTP output to Byte array</span>
WebContext.Response.BinaryWrite(outBuf);
<span style="color:green;">// close the output stream</span>
outputStream.Close();
<span style="color:green;">//end the processing of the current page to ensure that no other HTML content is sent</span>
WebContext.Response.End();

}


Finally, It would definitely be handy to be able to create a PDF Document from a PDF.Filestream to save having to play around with so many streams & I look forward to you merging concatenate and adding a save to web response method!

Thanks for your help

Jon

Hello Jon,

As specified in one of our online demos related to PDF file concatenation, you can save the resultant PDF to StreamObject and then have passed the contents of Stream object to HTTP response object. Do you still require us to add an overloaded method of PdfFileEditor.Concatenate(…) to save the resultant PDF in web response object ?

Hi there, absolutely include it because it simplifies the code dramatically for sending a PDF document to the browser (no 9 line hack playing with web headers) and it also then matches your Word and Cell component models.

As a side point, your concatenate function is only part of the PDF kit at the moment which is discontinued from October 2011 so have you any ETA when that complete functionality will be incorporated into the main PDF component so I can remove it from my object references?

Thanks for your help

Jon

Hello Jon,

As I have shared earlier, we have logged a new feature to save the resultant PDF document to Response object when using Document object to concatenate the PDF documents. It has been logged as PDFNEWNET-29779. Please take a look over following for information on how to use Document object to Concatenate PDF Files

Besides this, I have also logged the requirement to save the resultant PDF generated with Concatenate method to Response object as PDFNEWNET-29842 in our issue tracking system.

Nevertheless, Aspose.Pdf for .NET contains all the classes and methods (including Concatenate) of Aspose.Pdf.Kit component under Aspose.Pdf.Facades namespace. Please try using using it and in case you encounter any issue or you have any further query, please feel free to contact.

Thanks for your patience. Please note that the issues you have found earlier (filed as PDFNEWNET-29779;PDFNEWNET-29842) have been fixed in this update.


This message was posted using Notification2Forum from Downloads module by aspose.notifier.

Hi


I have question to output file on HTTPRespose stream. I am using the latest version of Aspose.Pdf(11.7.0). In there i cannot see the overloaded method for save same has you given the solution. I am see potential overloaded method as below to perform the similar job but i am not aware of what to supply the parameters and even there is no Hint or help to implement that.

public void Save(HttpResponse response, string outputFileName, ContentDisposition disposition, SaveOptions options);

Can you please help me in how to use this method.

Thanks
Amit Dhamiaj

Hi Amit,

Thanks for your inquiry. Please check sample usage code. Hopefully, it will help you to accomplish the task.

  • Document doc = new Document(“filename.pdf”);

    doc.Save(HttpContext.Current.Response, “test.pdf”, ContentDisposition.Inline, new PdfSaveOptions());

Please feel free to contact us for any further assistance.

Best Regards,