简体   繁体   English

如何在nuxt项目中下载pdf?

[英]How to download pdf in nuxt project?

 <div  style="height: 0;position:  fixed;  left: 50%; top: 0; transform: translateX(-50%);
       z-index: -1;overflow: hidden">
          <ticket-pdf v-if="pdfData" :pdfData="pdfData" :downloadBtn="downloadBtn"  @download="downloadBtn = $event"  />   </div>

In my nuxt project, i need to download pdf file in my main componet.When user clicked download button it will be downloaded directlty without previewing pdf component.在我的 nuxt 项目中,我需要在我的主要组件中下载 pdf 文件。当用户单击下载按钮时,它将直接下载而不预览 pdf 组件。 So i hide my ticket-pdf component inside my main component.所以我将ticket-pdf 组件隐藏在我的主要组件中。 This way works in localhost but when i published my project to test area it does not work.这种方式适用于本地主机,但是当我将我的项目发布到测试区域时它不起作用。 It download only 1 empty page.它只下载 1 个空白页面。 and i face with this mistake.我面临这个错误。

Failed to load resource: the server responded with a status of 500 ()

If i open my pdf file in a other page and i can preview and download it also.如果我在另一个页面中打开我的 pdf 文件,我也可以预览和下载它。 But i need to doownload it without routing anywhere and directly in my main component但我需要下载它而不在任何地方直接在我的主要组件中路由

  printPDF() {
            const html2canvasOptions = {
                allowTaint: true,
                removeContainer: true,
                imageTimeout: 15000,
                logging: true,
                useCORS: true,
                scrollX: 0,
                scrollY: 0,
                scale: 2,
            };
            // Initialize the PDF.
            let pdf = new jsPDF('p', 'in', [8.5, 11], false);
            let totalPage = 0
//i have many pages and countof pages changes . It depends. so firstly i calculate page count and create pdf.
            let pageCount = document.querySelectorAll('[id^=contentPrint]').length
             for (let i = 0; i < pageCount; i++) {

                const contentPrint = document.getElementById('contentPrint-' + i);
                html2canvas(contentPrint, html2canvasOptions)
                    .then((canvas) => {

                        const image = {type: 'jpeg', quality: 1};
                        const margin = [0.5, 0.5];

                        let imgWidth = 8.5;
                        let pageHeight = 11;

                        let innerPageWidth = imgWidth - margin[0] * 2;
                        let innerPageHeight = pageHeight - margin[1] * 2;

                        // Calculate the number of pages.
                        let pxFullHeight = canvas.height;
                        let pxPageHeight = Math.floor(canvas.width * (pageHeight / imgWidth));
                        let nPages = Math.ceil(pxFullHeight / pxPageHeight);
                        totalPage += nPages

                        // Define pageHeight separately so it can be trimmed on the final page.
                        pageHeight = innerPageHeight;

                        // Create a one-page canvas to split up the full image.
                        let pageCanvas = document.createElement('canvas');
                        let pageCtx = pageCanvas.getContext('2d');
                        pageCanvas.width = canvas.width;
                        pageCanvas.height = pxPageHeight;


                        for (let page = 0; page <= nPages; page++) {
                            // Trim the final page to reduce file size.
                            if (page === nPages - 1 && pxFullHeight % pxPageHeight !== 0) {
                                pageCanvas.height = pxFullHeight % pxPageHeight;
                                pageHeight = (pageCanvas.height * innerPageWidth) / pageCanvas.width;
                            }

                            // Display the page.
                            let w = pageCanvas.width;
                            let h = pageCanvas.height;
                            pageCtx.fillStyle = 'white';
                            pageCtx.fillRect(0, 0, w, h);
                            pageCtx.drawImage(canvas, 0, page * pxPageHeight, w, h, 0, 0, w, h);

                            // Add the page to the PDF.
                            if (page > 0) pdf.addPage();

                            let imgData = pageCanvas.toDataURL('image/' + image.type, image.quality);
                            pdf.addImage(imgData, image.type, margin[1], margin[0], innerPageWidth, pageHeight);

                        }

                    });
            }

            setTimeout(() => {
               // pdf.deletePage(totalPage + 1)
                pdf.save("e-ticket" + '.pdf')

            }, 3000)

            setTimeout(() => {
                this.$emit("download", this.download);
            }, 4000)
        },

This is how i create pdf area.这就是我创建 pdf 区域的方式。 When user clicked download button i create pdf and download it thanks to my props.当用户单击下载按钮时,我创建 pdf 并下载它,这要归功于我的道具。

    printPDF() {
            window.scrollTo(0, 0);
            // Initialize the PDF.
            let pdf = new jsPDF('p', 'in', [8.5, 11], false);
            let totalPage = 0
            let counter = 0
            let myArray = []
            let pageCount = document.querySelectorAll('[id^=contentPrint]').length

            for (let i = 0; i < pageCount; i++) {
                myArray.push('contentPrint-' + i)
            }

            for (let i = 0; i < pageCount; i++) {

                const contentPrint = document.getElementById('contentPrint-' + i);

                html2canvas(contentPrint, {
                    scale: 2, useCORS: true, allowTaint: true, scrollY: 0
                }).then((canvas) => {
.................
........
.....
                    counter = counter + 1;
                    callBack();
                })
            }

            const callBack = () => {
                if (myArray.length === counter) { 
                    pdf.save("filename" + '.pdf')
                    this.$emit("download", this.download);
                }
            }
        },

    

the problem was about my settimeout function.问题是关于我的 settimeout function。 ın there ı would call pdf.save before pdf created and sure every browser works in different speed.在创建 pdf 之前,我会调用 pdf.save 并确保每个浏览器都以不同的速度工作。 so if we use callback function after all process done, then we can obtain our pdf rpint所以如果我们在所有过程完成后使用回调 function ,那么我们可以获得我们的 pdf rpint

You could maybe try to simply put您也许可以尝试简单地说

<a href="/your_file.csv" download>

by putting your_file.csv into the static directory.通过将static your_file.csv

Not sure if it can be enough in your case, sorry if it's not.不知道在你的情况下是否足够,如果不是,对不起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM