0
我有這樣一個靜態方法,我使用iTextSharp的生成PDF ..生成PDF字節數組
public static byte[] createPDF(string htmlstr) {
var html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE html
PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
<head>
<title>Minimal XHTML 1.0 Document with W3C DTD</title>
</head>
<body>
" + htmlstr + "</body></html>";
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
MemoryStream msOutput = new MemoryStream();
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter.GetInstance(document, msOutput);
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(new StringReader(html));
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
byte[] buffer = new byte[msOutput.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = msOutput.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
msOutput.Close();
return ms.ToArray();
}
}
當我調試,我通過worker.Parse(new StringReader(html))
之後,MemoryStream.Length
不起作用。
我看過一些使用FileStream
的例子,但我不想創建一個新文件。爲什麼代碼錯誤?
謝謝克里斯。我看到我最初做錯了,你的解決方案也有所幫助。我想再次提一次我的問題。我遇到了一個itextsharp問題,它不支持style =「display:none」css,我已經遍佈了我想要從中生成PDF的HTML。有沒有辦法在生成PDF時隱藏HTML中的一些元素?任何幫助將不勝感激。 – shress1