问题
Good morning everybody,
I have a project which is supposed to be deployed on
sharepoint 2007 (wss 3.0) as a custom web part . It is
simply a button to convert a certain string to a pdf
file and send it to the user.I'm using c# .NET . I have
the following code:
HttpContext.Current.Response.AddHeader"ContentDispositio
n", "attachment;filename=foo.pdf");
HttpContext.Current.Response.AddHeader("Content-Length", bb.Length.ToString());
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.BinaryWrite(bb);
bb is a bytes array. And this is working fine regarding the "sending the file
to user" part.
The problem I'm facing is with the creation of the bytes
array. I don't know how to create a bytes array from a
string that could be converted to PDF. I tried using
iTextSharp, but for some reason i'm always facing an
error with this line:
Document d = new Document();
The web part gives me an error when it's deployed (File
not found).
Now i'm stuck. What is the appropriate way to convert
this string to pdf and send it to the user WITHOUT
STORING IT ANYWHERE!
Any help is highly appreciated & thank you in advance :)
回答1:
See if this helps in creating the byte array, i am using html parser to convert my xml document to pdf -
// Using iTextSharp to construct a PDF document
// Create a document-object
Document document = new Document(PageSize.A4);
// Create a writer that listens to the document
// and directs a XML-stream to a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms);
document.Open();
System.Xml.XmlTextReader _xmlr;
if (String.IsNullOrEmpty(errorMsg))
_xmlr = new System.Xml.XmlTextReader(new StringReader(GetTransferedData(content)));
else
_xmlr = new System.Xml.XmlTextReader(new StringReader(@"<html><body>Error Message:" + errorMsg + "</body></html>"));
iTextSharp.text.html.HtmlParser.Parse(document, _xmlr);
document.Close();
ms.Flush();
byte[] data = ms.ToArray();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
ms.Close();
}
来源:https://stackoverflow.com/questions/7962981/how-to-create-a-pdf-from-a-string-and-send-it-to-the-user