我有以下html代码:

<!DOCTYPE html>
<html>
    <body>
        <p>don't print this to pdf</p>
        <div id="pdf">
            <p><font size="3" color="red">print this to pdf</font></p>
        </div>
    </body>
</html>

所有我想做的是打印到pdf,无论在div中找到一个id为“pdf”。这必须使用JavaScript来完成。"pdf"文件会自动下载,文件名为"foobar.pdf"

我一直在使用jspdf来做到这一点,但它唯一的功能是“文本”,只接受字符串值。我想提交HTML到jspdf,而不是文本。


当前回答

这个例子效果很好。

<button onclick="genPDF()">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
    function genPDF() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');
    
        doc.save('Test.pdf');
    }
</script>

其他回答

使用pdfMake.js和这个Gist。

(我在这里找到了Gist和html-to-pdfmake包的链接,但我现在没有使用这个包。)

在npm安装pdfmake后,将Gist保存在htmlToPdf.js中,我这样使用它:

const pdfMakeX = require('pdfmake/build/pdfmake.js');
const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';
import htmlToPdf from './htmlToPdf.js';

var docDef = htmlToPdf(`<b>Sample</b>`);
pdfMake.createPdf({content:docDef}).download('sample.pdf');

备注:

My use case is to create the relevant html from a markdown document (with markdown-it) and subsequently generating the pdf, and uploading its binary content (which I can get with pdfMake's getBuffer() function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried. I am dissatisfied with the results I got from jsPDF.fromHTML() suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF. Using canvas based solutions (like the deprecated jsPDF.from_html() function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs. Direct markdown to pdf converters like md-to-pdf are server side only and would not work for me. Using the printing functionality of the browser would not work for me as I do not want to display the generated PDF but upload its binary content.

你可以使用autoPrint()并将输出设置为'dataurlnewwindow',如下所示:

function printPDF() {
    var printDoc = new jsPDF();
    printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});
    printDoc.autoPrint();
    printDoc.output("dataurlnewwindow"); // this opens a new popup,  after this the PDF opens the print window view but there are browser inconsistencies with how this is handled
}

如果你需要下载一个特定页面的PDF文件,只需添加这样的按钮

<h4 onclick="window.print();"> Print </h4>

使用window.print()打印整个页面,而不仅仅是一个div

我使用JSPDF和html2canvas进行CSS渲染,我导出特定div的内容,因为这是我的代码

$(document).ready(function () {
    let btn=$('#c-oreder-preview');
    btn.text('download');
    btn.on('click',()=> {

        $('#c-invoice').modal('show');
        setTimeout(function () {
            html2canvas(document.querySelector("#c-print")).then(canvas => {
                //$("#previewBeforeDownload").html(canvas);
                var imgData = canvas.toDataURL("image/jpeg",1);
                var pdf = new jsPDF("p", "mm", "a4");
                var pageWidth = pdf.internal.pageSize.getWidth();
                var pageHeight = pdf.internal.pageSize.getHeight();
                var imageWidth = canvas.width;
                var imageHeight = canvas.height;

                var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight;
                //pdf = new jsPDF(this.state.orientation, undefined, format);
                pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio);
                pdf.save("invoice.pdf");
                //$("#previewBeforeDownload").hide();
                $('#c-invoice').modal('hide');
            });
        },500);

        });
});

下面的方法对我的案例很有效。

隐藏页面的其他部分,如下例所示

@media print{
    body{
        -webkit-print-color-adjust: exact; // if you want to enable graphics
        color-adjust: exact !important; // if you want to enable graphics
        print-color-adjust: exact !important; // if you want to enable graphics
       
        * {
            visibility: hidden;
            margin:0;
            padding:0
        }
        .print_area, .print_area *{
            visibility: visible;
        }
        .print_area{
            margin: 0;
            align: center;
        }
        .pageBreak { 
           page-break-before : always; // If you want to skip next page
           page-break-inside: avoid;  // If you want to skip next page
         }
      }
    @page {
        size: A4; margin:0mm; // set page layout
        background-color: #fff;
    }
}

使用javascript的print函数来打印执行。

<button onclick="window.print()">Print</button>