I am trying to generate a PDF file from and HTML string and external css files and save the PDF to disk. As you can see from this example, I am using very simple html. I know the css files are getting read into the ccsResolver by viewing intellisense.
Here is the code I am using :
internal string Create(PdfDocumentDefinition documentDefinition)
{
MemoryStream output = new MemoryStream();
MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>Hello, World!</body></html>"));
string pathName = @WebConfigurationManager.AppSettings["StagingPath"] + documentDefinition.DocumentName + ".pdf";
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, output);
using (output)
{
using (document)
{
document.Open();
CssResolverPipeline pipeline = SetCssResolver(documentDefinition.CssFiles, document, writer);
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(input);
output.Position = 0;
}
Byte[] data = output.ToArray();
File.WriteAllBytes(pathName, data);
}
return pathName;
}
private CssResolverPipeline SetCssResolver(List<String> cssFiles, Document document, PdfWriter writer)
{
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
if (cssFiles != null)
{
foreach (String cssFile in cssFiles)
{
//cssResolver.AddCssFile(cssFile, true);
}
}
return new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
}
Here is the output as viewed in NotePad++ :
2 0 obj
<</Length 117/Filter/FlateDecode>>stream
xœ+ä*ä2гP€á¢t.c 256U0·0R(JåJã
ĪÊÜÒXÏÔHÁÌBÏÌBÁÐPÏ¢Ø@!¨¤Å)¤ÌÂÐH!$(¬khbè»*€„Ò¸4<RsròuÂó‹rR5C²€Š@J\C€ú¼i!*
endstream
endobj
4 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R>>>>/Contents 2 0 R/Parent 3 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
3 0 obj
<</Type/Pages/Count 1/Kids[4 0 R]>>
endobj
5 0 obj
<</Type/Catalog/Pages 3 0 R>>
endobj
6 0 obj
<</Producer(iTextSharp’ 5.5.7 ©2000-2015 iText Group NV \(AGPL-version\))/CreationDate(D:20151026102026-05'00')/ModDate(D:20151026102026-05'00')>>
endobj
xref
0 7
0000000000 65535 f
0000000311 00000 n
0000000015 00000 n
0000000399 00000 n
0000000199 00000 n
0000000450 00000 n
0000000495 00000 n
trailer
<</Size 7/Root 5 0 R/Info 6 0 R/ID [<055082e8139638e35ce08dedae069690><055082e8139638e35ce08dedae069690>]>>
%iText-5.5.7
startxref
657
%%EOF
I've been working on this for about 4 hours now. Can anyone see why it is not generating a valid PDF?