Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - Access a pdf file from views.py which is created by Js in a Django project

I am trying to render with HTML to pdf in my Django project. I am using html2pdf package form js and render my html into pdf by following link: youtubelink.

my template:

<div class="container-fluid py-5 bg-light">
  <div class="col-xl-10 bg-white" id="pdf_portion">
    <p>Lots of staff is in this div. I just skip those unnecessary things in this question.</p>
  </div>
</div>

<button class="btn btn-primary" id="download"> download pdf</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js"></script>

<script type="text/javascript">
  window.onload = function () {
    document.getElementById("download")
        .addEventListener("click", () => {
            const invoice = this.document.getElementById("pdf_portion");
            console.log(invoice);
            console.log(window);
            var opt = {
                margin: 0.8,
                filename: 'myfile.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 4 },
                jsPDF: { unit: 'in', format: 'A4', orientation: 'portrait' }
            };
            html2pdf().from(invoice).set(opt).save();
        })
  }
</script>

Here the 'download' button gives us the option to download the pdf. I need to send the pdf in my views.py in any method, thus I will able to save it in my database's filefield.

Please suggest How can I able to access that pdf file in my views.py.

question from:https://stackoverflow.com/questions/66050537/access-a-pdf-file-from-views-py-which-is-created-by-js-in-a-django-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The html2pdf package comes with the functionality to handle the generated pdf instead of directly downloading them. It's outputPdf function takes the desired data format as input and returns the output.

Currently supported data-formats are:

  • arraybuffer
  • blob
  • bloburi
  • datauristring
  • datauri

It can be used as followed:

const elem = document.getElementById('html'); //element whose pdf is to be made

html2pdf().from(elem).outputPdf('arraybuffer').then((result) => {
 // write your desired code here for sendin results to django views
});

Now in order to send this data to backend, you can simply use AJAX post request in this function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...