Afternoon,
I'm using PDFsharp to combine X number of PDFs into a single document. I'd like the final document to be downloaded to the client's browser as opposed to saving it to the web server.
Currently I have a button, when clicked, it fires a client-side event. The event gathers the selected keys in a gridview and returns an array of UNC file locations (these are the individual PDFs). Here's the code:
<script type="text/javascript">
function compilePDFLinks(s, e) {
var rowKeys = gridview1.GetSelectedKeysOnPage();
var arrayKeys = Object.values(rowKeys);
function clientSideMergePDFs(arrayKeys) {
PageMethods.MergePDFs(arrayKeys, onSuccess, onError);
}
function onSuccess(fileName) {
// Log success to browser console
window.open(fileName, "_blank");
}
function onError() {
// Log error to browser console
}
clientSideMergePDFs(arrayKeys);
}
</script>
I also have a ScriptManager on the page, so I can call my WebMethod to combine the PDFs.
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" LoadScriptsBeforeUI="true" runat="server" />
As for the WebMthod, it currently saves the combined PDF back to my web server. However, rather than saving it, I'd like the final document to be downloaded to the client's browser.
C#
[WebMethod]
public static object MergePDFs(params string[] arrayKeys) {
string uniqueID = Guid.NewGuid().ToString();
string targetPath = @"\\webServer\C$\sites\test\siteName\folder\pdfName_" + uniqueID + ".pdf";
string fileName = targetPath.Substring(x, targetPath.Length - x)
using (PdfDocument targetDoc = new PdfDocument()) {
foreach (string pdf in arrayKeys) {
using (PdfDocument pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
for (int i = 0; i < pdfDoc.PageCount; i++) {
targetDoc.AddPage(pdfDoc.Pages[i]);
}
}
}
targetDoc.Save(targetPath);
return fileName;
}
}
I'm not entirely sure what the easiest method is to accomplish this, downloading the file to the browser is new for me, so any help is greatly appreciated!
Thanks!
Edit: Answered my own question, thanks for the idea @psj01. Changes made:
- MergePDFs return type changed to 'object'
- MergePDFs adds a GuID to the end of the file name in targetPath
- fileName in targetPath extracted so it can be returned
- JS function accepts fileName as a parameter and opens it in a new window
- Created a powershell script to maintain folder size (cleans up old PDFs)