Как конвертировать HTML String в PDF, используя ConvertAPI (без физического файла) - PullRequest
0 голосов
/ 20 мая 2018

Ранее я использовал http://do.convertapi.com/Web2Pdf для преобразования HTML-строки в PDF с помощью простого запроса GET (не POST) с использованием Java.Весь контент был передан с использованием параметра curl.

Однако этот API, похоже, недавно перестал работать.Я пытаюсь перенести на https://v2.convertapi.com/web/to/pdf, но не могу найти пример, чтобы сделать то же самое, используя новый API с помощью GET или POST.

Может кто-нибудь предоставить пример для выполнения запроса GET или POST, используяJava?

ОБНОВЛЕНИЕ: мне удалось заставить его работать.

private static final String WEB2PDF_API_URL = "https://v2.convertapi.com/html/to/pdf";
private static final String WEB2PDF_SECRET = "secret-here";

String htmlContent = "valid HTML content here";

URL apiUrl = new URL(WEB2PDF_API_URL + "?secret=" + WEB2PDF_SECRET + "&download= attachment&PageOrientation=landscape&MarginLeft=0&MarginRight=0&MarginTop=0&MarginBottom=0");
HttpURLConnection connection = null;

ByteArrayOutputStream buffer = null;

connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestProperty("Content-Disposition", "attachment; filename=\"data.html\"");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestMethod("POST");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);

/* write request */
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(htmlContent);
writer.flush();
writer.close();

/* read response */
String responseMessage = connection.getResponseMessage();
logger.info("responseMessage: " + responseMessage);

int statusCode = connection.getResponseCode();
logger.info("statusCode: " + statusCode);

if (statusCode == HttpURLConnection.HTTP_OK) {
    logger.info("HTTP status code OK");
    // parse output

    InputStream is = connection.getInputStream();

    buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[16384];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    byte[] attachmentData = buffer.toByteArray();

    Multipart content = new MimeMultipart();

    ...

    MimeBodyPart attachment = new MimeBodyPart();
    InputStream attachmentDataStream = new ByteArrayInputStream(attachmentData);
    attachment.setFileName("filename-" + Long.toHexString(Double.doubleToLongBits(Math.random())) + ".pdf");
    attachment.setContent(attachmentDataStream, "application/pdf");
    content.addBodyPart(attachment);
    ...
}

1 Ответ

0 голосов
/ 20 мая 2018

Вы можете легко вставить строку HTML в файл.У меня нет примера JAVA, но демо C # даст вам правильный путь.

using System;
using System.IO;
using System.Net.Http;
using System.Text;

class MainClass {
  public static void Main (string[] args) {
    var url = new Uri("https://v2.convertapi.com/html/to/pdf?download=attachment&secret=<YourSecret>");
    var htmlString = "<!doctype html><html lang=en><head><meta charset=utf-8><title>ConvertAPI test</title></head><body>This page is generated from HTML string.</body></html>";
    var content = new StringContent(htmlString, Encoding.UTF8, "application/octet-stream");
    content.Headers.Add("Content-Disposition", "attachment; filename=\"data.html\"");
    using (var resultFile = File.OpenWrite(@"C:\Path\to\result\file.pdf"))
    {
        new HttpClient().PostAsync(url, content).Result.Content.CopyToAsync(resultFile).Wait();
    }
  }
}
...