如何在TCPDF PDF生成中使用外部CSS

16

我正在尝试使用tcpdf创建一个网页的pdf文件。但是它没有生效。这个页面是由php、外部css和javascript文件组成的。

是否有人能够帮我解决这个问题。

谢谢!

2个回答

30

在您添加HTML内容之前,可以按照以下方式包含外部CSS文件:

$html .= '<style>'.file_get_contents(_BASE_PATH.'stylesheet.css').'</style>';

这样,在将$html传递以生成PDF时,它将包括这些样式。

据我所知,在PDF中不需要包含Javascript。 PDF的目的是显示非交互式静态内容,这可以通过HTMLCSS实现。


1
你用哪个版本的TCPDF进行了测试? - Kunal Dethe
1
请注意,这会将样式表附加到HTML中。 您应该使用以下内容作为前缀...$html = '<style>'.file_get_contents(_BASE_PATH.'stylesheet.css').'</style>' . $html; - Rob
3
对我没有用。CSS文件内容被追加了,但没有生效。是否有其他的解决方法? - Annapurna

0
public byte[] GetPDF(string pHTML)
        {
            byte[] bPDF = null;

            MemoryStream ms = new MemoryStream();
            TextReader txtReader = new StringReader(pHTML);

            // 1: create object of a itextsharp document class
            Document doc = new Document(PageSize.A4, 25, 25, 25, 25);

            // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
            PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

            // 3: we create a worker parse the document
            HTMLWorker htmlWorker = new HTMLWorker(doc);

            // 4: we open document and start the worker on the document
            doc.Open();
            htmlWorker.StartDocument();

            // 5: parse the html into the document
            htmlWorker.Parse(txtReader);

            // 6: close the document and the worker
            htmlWorker.EndDocument();
            htmlWorker.Close();
            doc.Close();

            bPDF = ms.ToArray();

            return bPDF;
        }

3
好的,我会尽力满足您的需求。以下是需要翻译的内容:add some description on your solution在您的解决方案中添加一些描述 - Basil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接