Using dompdf with absolute links

2020-03-31 04:18发布

问题:

I am using the standard DOMPDF code to render existing web pages (e.g.1):

$dompdf = new DOMPDF();
$dompdf->set_base_path($artpath);
$dompdf->load_html_file($artpath);
$dompdf->render();
$dompdf->stream($pdfpath);

where $artpath' is the path to the HTML code and $pdfpath is the name of the PDF.

However, the web page contains both relative links (which are correctly followed) and absolute links (e.g. /gifs/bullet.gif) which are not found. This is probably because the DOMPDF code is being executed at http://www.epress.ac.uk/src/xtra/makeapdf.php, www.epress.ac.uk being a virtual domain on my server, which also hosts the virtual domain jasss.soc.surrey.ac.uk (that is, both domains are on the same server). It would seem that DOMPDF is using the document root of www.epress.ac.uk, when it should be using the document root of jasss.surrey.ac.uk.

Is there some way around this? I have tried resetting $_SERVER['DOCUMENT_ROOT'] to the document root of jasss.soc.surrey.ac.uk before calling new DOMPDF(), but this doesn't seem to solve the problem. I get errors such as:

file_get_contents(/styles/jasssarticle.css) [function.file-get-contents]: failed to open stream: No such file or directory

Unable to load css file /styles/jasssarticle.css

The web page is valid HTML according to the www validator.w3.org

Thanks for your advice!

回答1:

You're loading a file via the file system. That means all references to external files that don't include a domain part in the path are rendered relative to the file system. You can reference files in three ways:

  • Full URL (including domain), e.g. http://example.com/image.png. These are always read from the URL specified.
  • Absolute path, e.g. /file/path/image.png. This is read relative to the root of the file system, not the root of the web site, or the user's home directory (in the case of shared hosting).
  • Relative path (no leading slash), e.g. file/path/image.png. This is read relative to the HTML file. So in your case the file would be read from /Volumes/Documents/VirtualSites/jasss/16/2/file/path/image.png.

Calling $dompdf->set_base_path() only affects the relative path.

You'll have to modify the absolute file references to include the path to the website root, e.g. /Volumes/Documents/VirtualSites/jasss/styles/jasssarticle.css, or load the file via the website, e.g. http://jasss.soc.surrey.ac.uk/16/2/1.html.