|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "mime" |
| 6 | + "mime/multipart" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | +) |
| 10 | + |
| 11 | +// Example of DOCX to PDF conversion using vanilla go. |
| 12 | +// File is converted without temporary storing files on ConverAPI servers. |
| 13 | +// No error handling to make an example easier to read. |
| 14 | +// No file buffering to memory. To store file to memory in general is a bad idea! |
| 15 | +func main() { |
| 16 | + pipeReader, pipeWriter := io.Pipe() |
| 17 | + multipartWriter := multipart.NewWriter(pipeWriter) |
| 18 | + |
| 19 | + // Adjust URL according your converter and set YOUR_SECRET. |
| 20 | + req, _ := http.NewRequest("POST", "https://v2.convertapi.com/convert/docx/to/pdf?secret=YOUR_SECRET", pipeReader) |
| 21 | + req.Header.Set("Content-Type", multipartWriter.FormDataContentType()) |
| 22 | + req.Header.Set("Accept", "multipart/mixed") |
| 23 | + |
| 24 | + go func(mpWriter *multipart.Writer) { |
| 25 | + defer pipeWriter.Close() |
| 26 | + defer multipartWriter.Close() |
| 27 | + filePart, _ := mpWriter.CreateFormFile("file", "test.docx") |
| 28 | + f, _ := os.Open("assets/test.docx") // Open file that needs to be converted |
| 29 | + defer f.Close() |
| 30 | + f.WriteTo(filePart) |
| 31 | + // If conversion takes multiple source files, it can be added here, as an example above. |
| 32 | + }(multipartWriter) |
| 33 | + |
| 34 | + resp, _ := http.DefaultClient.Do(req) |
| 35 | + save(resp, "/tmp/result.pdf") |
| 36 | +} |
| 37 | + |
| 38 | +func save(resp *http.Response, file string) { |
| 39 | + defer resp.Body.Close() |
| 40 | + |
| 41 | + mediaType := resp.Header.Get("Content-Type") |
| 42 | + _, params, _ := mime.ParseMediaType(mediaType) |
| 43 | + multipartReader := multipart.NewReader(resp.Body, params["boundary"]) |
| 44 | + |
| 45 | + part, _ := multipartReader.NextPart() |
| 46 | + resFile, _ := os.Create(file) |
| 47 | + defer resFile.Close() |
| 48 | + io.Copy(resFile, part) |
| 49 | + // If conversion returns multiple files, it can be red using multipartReader.NextPart() multiple times. |
| 50 | +} |
0 commit comments