Создать документ (один)
PDF4me Создать документ (один) Создает единый документ путем объединения шаблона (Word, HTML, или PDF) с полезной нагрузкой данных (JSON, XML, или CSV) в одном REST звонок. Шаблон может быть Base64, общественное URLили сырой HTMLДанные могут представлять собой встроенный текст, Base64закодированный файл или URLВозвращает отрендеренный результат. PDF, Docx, или HTML в двоичном виде (200) или через Location-заголовок опроса URL (202).
Аутентификация вашего API Запрос
Каждый PDF4me REST В звонке необходимо указать ваш API ключ в Authorization В заголовке используется базовая аутентификация. Получите или измените свой ключ на панели разработчика.
Конечная точка
/api/v2/GenerateDocumentSingleВажные факты, которые нельзя пропустить
documentDataText или documentDataFiledocumentDataText для встроенного JSON / XML / CSV. Использовать documentDataFile для Base64-закодированный файл данных или общедоступный URL.PDF или DocxHTML принимает HTML Только PDF. Принимаются PDF-файлы. PDF Только. Точный корпус имеет значение.IsAsync: true тот API может ответить кодом 202 и заголовком Location. GET что URL (то же разрешение) до 200 с отрендеренным файлом (стандартный) pdf4meAsyncRequest шаблон).HTTP настраивать
Метод: ПОЧТА
URL: https://api.pdf4me.com/api/v2/GenerateDocumentSingle
Content-Type: приложение/json
Авторизация: Базовый <ваш PDF4me API ключ>
Отправлять IsAsync: true в организме. 200 Возвращает количество байтов, отображаемых в файле. 202 возвращает Расположение заголовок с опросом URL; GET что URL с тем же заголовком Authorization до 200.
Матрица вариантов (применимо к Postman)
Выберите один вариант шаблона (T1 / T2 / T3) и один вариант данных (D1 / D2 / D3). Шесть комбинаций охватывают каждый вызов.
Шаблон (templateFileData)
| Код | Источник | Ценность почтальона в templateFileData | Также требуется |
|---|---|---|---|
| T1 | Base64 | Base64 template file (strip data:...;base64, prefix if present) | templateFileName |
| T2 | URL | Full HTTPS URL string (not downloaded by the API request body) | templateFileName |
| T3 | HTML code | Base64-encoded UTF-8 HTML: Buffer.from(html, "utf8").toString("base64") | templateFileName, templateFileType: HTML |
Данные документа (один из двух) API поля)
| Код | Источник | поле API | Ценность почтальона |
|---|---|---|---|
| D1 | Text | documentDataText | Raw JSON / XML / CSV string |
| D2 | Base64 | documentDataFile | Base64 of the data file (strip data-URL prefix if present) |
| D3 | URL | documentDataFile | Full HTTPS URL to .json / .xml / .csv |
Правило: ровно один из documentDataText или documentDataFile Необходимо установить значение. Неиспользуемое поле следует исключить из текста сообщения.
Распространенные комбинации
| # | Шаблон | Данные | Типичное использование |
|---|---|---|---|
| 1 | T1 Docx base64 | D1 JSON text | Word mail-merge to PDF |
| 2 | T2 Docx URL | D3 JSON URL | Hosted template + hosted data |
| 3 | T3 HTML | D1 JSON text | HTML mustache rendered to HTML / PDF |
| 4 | T1 PDF form | D2 JSON base64 | PDF template + encoded data file |
| 5 | T2 MailMerge URL | D1 XML text | Word merge fields + inline XML |
templateFileType → разрешенный outputType
templateFileType | Допустимый outputType | Примечания |
|---|---|---|
Docx | PDF, Docx | PDF4me Word template |
MailMerge | PDF, Docx | Mail merge Word |
GoogleDocs | PDF, Docx | Google Docs export style |
HTML | HTML only | Mustache in HTML |
PDF | PDF only | PDF form / template |
API поля тела
Всегда отправляется
| Параметр | Необходимый | Что это делает | Пример |
|---|---|---|---|
| jobIdExt | Optional | Your own reference for this call. It is stored with the API call log so you can correlate calls with your jobs. Type: string. | |
| integrations | Optional | Integration identifiers, forwarded unchanged with the job's notification settings. Type: array. | |
| isAsync | Optional | Set to `true` to process the action asynchronously and get a job to poll at `/api/v2/GetActionStatus`. Only honoured by actions that support asynchronous processing. Type: boolean. | true |
| templateFileType | Optional | Type of the template file, e.g. `Docx`, `Html` or `Pdf`. Not used by GenerateDocumentSingleV2. | Docx, HTML, PDF, MailMerge, GoogleDocs |
| templateFileData | Optional | Required. The template file. Accepts the base64-encoded file content, a `pdf4meblobid://<id>` reference, or an `https` URL. Not used by GenerateDocumentSingleV2, which loads the stored template named by `templateFileName`. Type: string. | Base64 template, or template URL string |
| documentDataType | Optional | Format of the data, `Json`, `XML` or `Csv`. | Json, XML, or Csv (exact casing) |
| templateFileName | Optional | Required. File name of the template, including its extension. For GenerateDocumentSingleV2 it is the name of a template uploaded in the PDF4me Dashboard (https://dev.pdf4me.com/dashboard/#/document-template/), which is loaded instead of `templateFileData`. Type: string. | With extension, e.g. template.docx, template.html, template.pdf |
| documentDataText | Optional | The data as text. Used when `documentDataFile` is empty. Type: string. | Valid JSON when documentDataType is Json; XML must look like XML; CSV non-empty |
| documentDataFile | Optional | The data as a file. Accepts the base64-encoded file content, a `pdf4meblobid://<id>` reference, or an `https` URL. Takes precedence over `documentDataText`. Type: string. | Base64 data file or URL to data file |
| outputType | Optional | Format of the generated document, e.g. `pdf` or `docx`. Not used by GenerateDocumentSingleV2. | PDF, Docx, or HTML (see allowed-output table above) |
| metaDataJson | Optional | Optional document metadata as a JSON string. Type: string. | |
| keepPdfEditable | Optional | Keep form fields editable when the output is a PDF. Type: boolean. | false |
Примеры полезных нагрузок
1. Шаблон Word (base64) + JSON текст → PDF
{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "Json",
"documentDataText": "{\"name\": \"John Doe\", \"email\": \"[email protected]\", \"items\": [{\"product\": \"Widget\", \"price\": 29.99}]}",
"outputType": "PDF",
"KeepPdfEditable": false,
"IsAsync": true
}
2. Шаблон Word (URL) + JSON данные (URL) → PDF
{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "https://example.com/template.docx",
"documentDataType": "Json",
"documentDataFile": "https://example.com/data.json",
"outputType": "PDF",
"KeepPdfEditable": false,
"IsAsync": true
}
3. Шаблон Word (base64) + JSON данные (base64) → вывод в формате Word
documentDataFile содержит 64-битную систему счисления JSON байты файла (а не разобранный объект).
{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "Json",
"documentDataFile": "eyJuYW1lIjogIkpvaG4gRG9lIn0=",
"outputType": "Docx",
"IsAsync": true
}
4. HTML шаблон (base64 из HTML файл) + JSON текст → HTML
Для сырого HTML В Postman отправьте тот же самый полезный груз. n8n узел будет: закодирован в формате base64 HTML в templateFileData.
{
"templateFileType": "HTML",
"templateFileName": "template.html",
"templateFileData": "PCFET0NUWVBFIGh0bWw+...",
"documentDataType": "Json",
"documentDataText": "{\"title\": \"Invoice\", \"heading\": \"Hello\", \"content\": \"World\"}",
"outputType": "HTML",
"IsAsync": true
}
5. Слияние почты (URL) + XML текст → PDF
{
"templateFileType": "MailMerge",
"templateFileName": "template.docx",
"templateFileData": "https://example.com/template.docx",
"documentDataType": "XML",
"documentDataText": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><name>John Doe</name><email>[email protected]</email></root>",
"outputType": "PDF",
"IsAsync": true
}
6. PDF шаблон формы (base64) + CSV текст → PDF (редактируемый)
{
"templateFileType": "PDF",
"templateFileName": "template.pdf",
"templateFileData": "JVBERi0xLjQKJcfsj6IK...",
"documentDataType": "Csv",
"outputType": "PDF",
"KeepPdfEditable": true,
"IsAsync": true
}
7. Стиль Google Docs (base64) + JSON URL → Docx
{
"templateFileType": "GoogleDocs",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "Json",
"documentDataFile": "https://example.com/data.json",
"outputType": "Docx",
"IsAsync": true
}
Советы по сбору почты
пример curl
curl -X POST https://api.pdf4me.com/api/v2/GenerateDocumentSingle \
-H "Content-Type: application/json" \
-H "Authorization: Basic YOUR_API_KEY" \
-d '{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "https://example.com/template.docx",
"documentDataType": "Json",
"documentDataFile": "https://example.com/data.json",
"outputType": "PDF",
"KeepPdfEditable": false,
"IsAsync": true
}' \
--output generated.pdf
Краткий справочник: обязательные и необязательные опции в зависимости от варианта
| Поле | Т1+Д1 | Т2+Д3 | Т1+Д2 | Т3+Д1 | Любой PDF-файл |
|---|---|---|---|---|---|
templateFileType | Req | Req | Req | Req | Req |
templateFileName | Req | Req | Req | Req | Req |
templateFileData | Req (b64) | Req (URL) | Req (b64) | Req (b64 HTML) | Req |
documentDataType | Req | Req | Req | Req | Req |
outputType | Req | Req | Req | Req | Req |
documentDataText | Req | Omit | Omit | Req | Omit |
documentDataFile | Omit | Req (URL) | Req (b64) | Omit | Omit |
IsAsync | Req | Req | Req | Req | Req |
KeepPdfEditable | Opt | Opt | Opt | N/A* | Opt if PDF |
*KeepPdfEditable применяется только когда outputType является PDF; API В противном случае это ложно.