Save to PDF Using Pdfcrowd

Pdfcrowd is a HTML to PDF creation sevice wich lets you create PDF from web pages and raw HTML code. You can also convert HTML to PDF online. They also provide a free save to PDF service – a strightforward way to save your web pages to PDF. What you need to do is place the code below into your HTML. When clicking the link, the containing page will be converted to a PDF document. The service will retrieve the URL of the page to convert from the HTTP referer.

<a href="http://pdfcrowd.com/url_to_pdf/" rel="nofollow">Convert to PDF</a>

Convert this page to PDF

I ran into a scenario when I needed the free service, having the link on one page but convert another. To do so the HTTP referer needs to be modified.

Using C#

The System.Net.WebClient allows us to easily make a request with a modified referer header and download the created PDF data from the Pdfcrowd service. The PDF bytes are written to the response output stream.

using (var client = new WebClient())
{
    client.Headers.Add("Referer", "http://domain.com");
    byte[] pdfBytes = client.DownloadData("http://pdfcrowd.com/url_to_pdf/");
 
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=mypdf.pdf");
    Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
    Response.End();
}

Using PHP

In PHP the approach is pretty much the same. Create a streaming context and set the URL referer. Send a http request to the Pdfcrowd service URL using the stream context. Set headers and write the binary PDF data to the output buffer.

$context = stream_context_create(array(
    'http' => array(
        'method'=> 'GET',
        'header' => 'Referer: http://domain.com'
    )
));
 
$fp = fopen('http://pdfcrowd.com/url_to_pdf/', 'r', false, $context);
 
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=mypdf.pdf');
 
fpassthru($fp);
 
fclose($fp);