wkhtmltopdf use wkhtmltopdf generate and download the pdf

Copyright: https://blog.csdn.net/qq_21852449/article/details/90255811

Project requirements to export pdf report, previously used canvas transfer pdf report too much but when the time will go wrong, so changed the background to deal with. wkhtmltopdf it clear from the name of point of view, the use webkit html rendering into a pdf. As the level of dish so in their own development process continue to fall pit, now sum up hoping to help small partners encounter the same problem.
1. Install articles
wkhtmltopdf can be described as powerful, full of loopholes, might not his reason, after all, depend on webkit external program. So when will we downloaded optimistic version to install ubuntu for example, the command line lsb_release -a
Here Insert Picture Description
can be seen Codename: bionic, go wkhtmltopdf official website to download the specified version of the deb package, if it is a remote server, wget directly to the server just fine and then sudo apt install <download file>install the package. Download page, it reads: Here Insert Picture Description
So let's follow the provisions of the downloaded xvfb sudoo apt install xvfb, so the environment is ready, we will execute the final aim wkhtmltopdf command in xvfb environment.

2. Use the articles acquire Baidu example, if you do enough of a good character is so simple xvfb-run wkhtmltopdf www.baidu.com baidu.pdf, you will open the Baidu home page is generated in the current directory harvest pdf a pdf file. This time everything is in place, but many times we went to the conversion page is a complex dynamic pages with complex javascript need to be performed before converting, wkhtmltopdf -Hview documents there in the page options in the --window-status <...>argument, which means that only when you the js program explicitly call window.status = <...> only value the same time wkhtmltopdf only to render the page, this is a black & wkhtmltopdf Yeah. Also, if you look carefully you will find that it also supports reading and writing documents cookies so privileged encounter pages need not be afraid.

3. Call chapter
Next Our aim is to call a golang wkhtmltopdf, does have a corresponding library but a complete command of thing would not have trouble looking for third-party libraries on github, do not give yourself too much dependent on the introduction of the program, otherwise problematic. The following code is doing is in accordance with the user given url generate a pdf file locally, and only when the js in window.status='ready'time before going to render the page

func generateExec(url string, pdfFile string) error {
	c := "xvfb-run wkhtmltopdf --window-status ready    " + htmlFile + "  " + pdfFile
	cmd := exec.Command("sh", "-c", c)
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

We call this function generateExec("www.baidu.com","aim.pdf"), so now we have a local file name is aim.pdf, the goal now is to put this file passed to the foreground program. In golang is very simple, get three lines.

	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File(fileName)

c.File => File writes the specified file into the body stream in a efficient way.
From the point of view c.File annotation function, access request should be post.

4 preceding chapter
now has the background Ok we just need to create a request to visit an excuse like, assuming you are using vue + axios, then two things 1. Access the appropriate way to post2 type to arraybuffer, pay attention to me this function this.$route.param.id 、测试报告.pdfare my own configuration, you need to replace your own.

axios({
          method: 'post',
          url: process.env.API_BASE + '/version/shared-report-byte',
          data: { id: this.$route.params.id },
          responseType: 'arraybuffer',
          timeout: 300 // request timeout

        }).then(function(response) {
          if (!response.data) {
            return
          }
          let url = window.URL.createObjectURL(new Blob([response.data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '测试报告.pdf')
          document.body.appendChild(link)
          link.click()
     
        }).catch(function(error) {
          console.log(error)
        })

The final step is where you like to export html pages added windiw.status='ready'to control when to render the wkhtmltopdf.
Having said all this, or I wish smooth. After all wkhtmltopdf powerful, full of loopholes.

Guess you like

Origin blog.csdn.net/qq_21852449/article/details/90255811