创建一个按钮,允许用户将页面保存为文件? [关闭]

Is there any good way to have a button that lets users save a page as a file for clean viewing later, likely as PDF? Needs to respect @media print CSS.

Options considered:

  1. http://www.web2pdfconvert.com - styling is ultra-basic and doesn't take account of @media print - would be acceptable if it used the @media print CSS
  2. "Print" button that triggers print to file, e.g. Microsoft XPS Document Writer - my understanding is that this is not doable, and if users understood they could easily print to a file they wouldn't need a button
  3. Word doc - has the advantage of being editable, but my understanding is this is hugely complex, especially with dynamic formatting
  4. Button opens a separate PHP file that serves a pdf, as using http://www.fpdf.org/ - my understanding is there would be a ton of work recreating the formatting I've already made with CSS, and may not be able to get 100% there
  5. Save html viewable with Word - awkward to email since CSS in separate file, and Word handles CSS poorly anyway

Is there a simpler way that I'm missing? Or a good way to get past the obstacles I found with one of these options?

I've had to do this before, so I know your pain. Let me tell you about my solution, and then give you the proper code.

I decided to have users download a PDF of the entire page. I wanted to have a library that renders HTML to PDF. In addition, I knew I'd need different CSS for this than my core site. But, I didn't want to duplicate it (like media queries support... for making new line breaks, etc). So, I ended up using dompdf, the media type of projector, and loaded my website by loading the same page of mine using some built in tools of Zend Framework. (ZF is not required for this solution).

Let's do this (oh - and yes, this isn't PERFECT but it'll get you pretty close!)

1) download domPDF

2) In dompdf_config.custom.inc.php file, uncomment or add or whatever the following line (yes, this isn't perfect, but I don't know many projectors that use this media type):

define("DOMPDF_DEFAULT_MEDIA_TYPE", "projection");

3) Then, modify your CSS to have the media query:

@media projection {
    // all of your css to make sure this works fine - like page breaks
}

4) And of course, finally get your entire page using something like file_get_contents() or curl.

Here's what my final bit of code looks like ($html = the entire content of the page to save)

require_once(APPLICATION_PATH . '/../library/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->set_protocol('http://');
$dompdf->set_host($options->domain);
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream('Printed.pdf');