Próbuję przekonwertować część mojej strony internetowej na pdf przy użyciu iTextSharp, a podczas generowania kodu PDF poprawnie działa, żaden styl CSS nie jest stosowany. Próbowałem stosować style jeden po drugim, ale to nie działa. Oto, do czego do tej pory doszedłem:Style CSS nie są stosowane do plików PDF za pomocą iTextSharp
//Get the portion of the page to convert.
StringBuilder sb = new StringBuilder();
print_div.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string html = sb.ToString();
//Generate a random filename to use for the pdf
Guid random_guid;
random_guid = Guid.NewGuid();
string fileName = random_guid.ToString() + ".pdf";
string filename_with_folder = @"pdf\sl_" + fileName;
string fullFilePath = System.IO.Path.Combine(Request.PhysicalApplicationPath, filename_with_folder);
using (Document doc = new Document())
{
// Create the pdf
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
doc.Open();
try
{
//Set the font size for all elements
StyleSheet styles = new StyleSheet();
styles.LoadStyle("body", "fontsize", "8px");
//Write the content to the pdf document
StringReader sr = new StringReader(html);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
}
catch (Exception ex)
{
}
doc.Close();
}
Czy czegoś brakuje? Zacząłem używać HTMLWorker i przełączyłem się na XMLWorker, ale myślę, że teraz się po prostu mylę. Pomoc byłaby doceniona.
ATTEMP # 2
Dzięki za odpowiedź! Oto, co wymyśliłem, ale to nie działa. Moje treści nie pojawiają się teraz w pliku pdf i nie jestem pewien dlaczego. jakieś pomysły?
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
doc.Open();
// CSS
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/print.css"), FileMode.Open));
cssResolver.AddCss(cssFile);
// HTML
CssAppliers ca = new CssAppliersImpl();
HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// PIPELINES
PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
StringReader sr = new StringReader(html);
p.Parse(sr);
doc.Close();
}
Czy jestem blisko, czy też zupełnie brakuje mi tego punktu?
Pierwsze pytanie, poprawnie sformatowany kod, pokazujący wypróbowany, krótki i dokładny opis. To na pewno jest rzadkie. – gunr2171
Rozwiązałeś to? Opublikuj odpowiedź lub przewodnik, co zrobić? Mam taką samą sytuację jak ty .... – micronyks