How can I save a styled DIV as a PDF

1.6k views Asked by At

Hi Is there a way to save a styled DIV as a PDF using Javascript or HTML?

I've got a styled DIV and I would like to be able to save it as a PDF with a click of a button I would also like it to keep it's styles.

How can this be done?

Thanks

    <style>
    .spOutputbox {
        margin: 5px 0 0 40px;
        padding: 10px;
        width: 378px;
        height: 568px;
        border-radius: 5px;
        font-size: 15px;
        color: #333;
        box-shadow: 0 1px 5px rgba(0,0,0,0.25);
        background: #f5f5f5;
        text-align: center;
        float: left;
    }
    .outline {
        border: 1px dotted #000;
    }
    .spOutputbox .ribbon {
        margin-top: 20px;
        width: 100%;
        height: 40px;
        border-top: 1px dotted #000;
        border-bottom: 1px dotted #000;
    }
    .spOutputbox .tableTitle {
        margin: 30px 0;
        font-size: 30px;
        font-weight: normal;
    }
    .spOutputbox .pname {
        margin: 10px 0;
        font-size: 18px;
        font-weight: normal;
    }
    </style>

    <div class="spOutputbox">
        <div class="outline">
           <div class="ribbon"></div>
           <div class="spContent">
           <div class="tableTitle">Table 1</div>
           <div class="pname">Name 1</div>
           <div class="pname">Name 2</div>
           <div class="pname">Name 3</div>
           <div class="pname">Name 4</div>
        </div>
    </div>
    <button id="makepd">generate PDF</button>
1

There are 1 answers

4
jenjis On

Maybe Html2Canvas could help you:

with this library you should be able to convert the div in a canvas, and then, using the code like the sample:

var imgData = canvas.toDataURL('image/jpeg');
var doc = new jsPDF('landscape');

doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
doc.save('sample-file.pdf');

save the div as image on pdf

for further information take a look to this jsPDF post