Before, we developed a pedestrian monitoring system in a scenic spot. After the system went online, we continued to adjust and optimize it, and it has maintained a stable operation. Now, the scenic spot needs to make a website, in which the statistics of the number of people at each time point in a day can be viewed and a PDF can be generated for download and viewing. Since we use Go language on the server side, so here we use a Go-wkHTMLTopdf to achieve this function.

Generate the first PDF in the desired format (no problem) :

The second time the PDF is generated, the following error appears:

The following error message appears when viewing the console application:

PDF generation code:

func WritePDFFile(htmlPath, pdfPath string) error { if err := pdf.Init(); err ! = nil { return err } pdf.Destroy() // Create object from URL. object2, err := pdf.NewObject(htmlPath) if err ! = nil { return err } // Create converter. converter, err := pdf.NewConverter() if err ! = nil { return err } defer converter.Destroy() // Add created objects to the converter. converter.Add(object2) // Set Converter Options. Converter.Title = "Headcount" converter converter.MarginTop = "1cm" converter.MarginBottom = "1cm" converter.MarginLeft = "10mm" converter.MarginRight = "10mm" // Convert objects and save the output PDF document. outFile, err := os.Create(pdfPath) if err ! = nil { return err } defer outFile.Close() if err := converter.Run(outFile); err ! = nil { return err } return nil }Copy the code

The above code initializes the PDF instance in the function and destroys the function. When you call the download PDF interface, there is no error in the first call, but the second call will not be in the main thread, so you need to instantiate the initial PDF instance in the main thread first, you can solve the problem.

There are two solutions to generate PDFS:

1. Initialize instances in the main function.

2, use exe command directly convert PDF, this is also the simplest method.