16

I am trying to create a pdf of a web page with tcpdf. But it's not working. The page is a php with external css and javascript files.

Can anyone help me with this.

Thanks,

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
user1559230
  • 2,790
  • 5
  • 26
  • 32

2 Answers2

30

To include external CSS file, you can do as below before you add your HTML content

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

By this, while you pass $html to generate pdf it will include those styles.

As far I am aware, there is no need for including Javascript into a PDF. The purpose of a PDF is to display a non-interactive static content, which can be achieved by HTML and CSS

Saravanan
  • 1,879
  • 2
  • 27
  • 30
  • 1
    which version of tcpdf did you test it with? – Kunal Dethe May 09 '14 at 05:51
  • 1
    Note that this appends the style sheet to the HTML. You should prepend it by using.. `$html = '' . $html;` – Rob Feb 29 '16 at 12:12
  • 3
    Doesn't work for me. The css file contents are appended, but not implemented. Is there any other work around? – Annapurna Oct 25 '17 at 09:56
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;
        }