【发布时间】:2015-10-11 05:01:56
【问题描述】:
这个问题与我向here 提出的问题有关“如何提示用户从 Sharepoint 页面输入保存位置?”
我需要做的是,在生成 PDF 之后:
private void GeneratePDF(List<ListColumns> listOfListItems)
{
. . .
//Create a stream that we can write to, in this case a MemoryStream
StringBuilder sb = new StringBuilder();
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 25, 25, 10, 10))
{
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
Paragraph docTitle = new Paragraph("UCSC - Direct Payment Form", timesBold16UCSCBlue);
doc.Add(docTitle);
Paragraph subTitle = new Paragraph("(Not to be used for reimbursement of services)", timesRoman9Font);
subTitle.IndentationLeft = 20;
doc.Add(subTitle);
. . . // tons of iTextSharp PDF-generation code elided for brevity
String htmlToRenderAsPDF = sb.ToString();
//XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(htmlToRenderAsPDF))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
doc.Close();
}
}
try
{
var bytes = ms.ToArray();
// This is currently saved to a location on the server such as C:\Users\TEMP.SP.005\Desktop\iTextSharpTest.pdf (but the number (such as
"005" irregularly increments))
String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
String fileLinkBase = "Generated PDF: <a href=\"{0}\">{1}</a>";
String filelink = String.Format(fileLinkBase, fileFullpath, pdfFileName);
File.WriteAllBytes(fileFullpath, bytes);
var pdflink = new Label
{
CssClass = "finaff-webform-field-label",
Text = filelink
};
this.Controls.Add(pdflink);
}
catch (DocumentException dex)
{
throw (dex);
}
catch (IOException ioex)
{
throw (ioex);
}
catch (Exception ex)
{
throw (ex);
}
}
} // GeneratePDF
...让用户有机会将该文件保存到他们的本地计算机(目前,它正在保存在服务器上)。
IOW,我基本上想做的就是替换这一行:
String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
...类似于:
String fileFullpath = "Hey, bloke (or blokette), where do you want to save this?"
这显然是可能的,甚至有些普遍,因为许多网站会为您生成文件,然后允许您保存这些文件
生成的文件到您选择的位置或默认位置,例如您的下载文件夹。
服务器端 (C#) 或客户端 (jQuery) 解决方案都可以接受,但我更喜欢服务器端,因为这是生成 PDF 的地方。
【问题讨论】:
-
摆脱你的
catch块。 -
您的服务器无法写入用户的磁盘。相反,您需要通过 HTTP 响应提供文件作为下载。
-
为什么? (摆脱我的 catch 块)
-
是的,这就是我想要做的 - 使文件可供下载。我将更新问题标题。
-
我想进一步补充一下@SLaks 关于
try/catch的说法,并说你应该只try一些东西,并且尽可能少的东西,可能会失败,只有@987654328 @它,如果您有一个与默认不同的明确恢复计划。您的代码正在尝试 11 种类似的事情,包括在MemoryStream上调用ToArray(),除非宇宙射线击中机器,否则它永远不会抛出,还设置使用您自己的逻辑且未在catch语句中明确处理的字符串反正
标签: c# jquery sharepoint-2010 itextsharp filesaver.js