Перейти к основному содержимому

Создать документ (один)

Что делает эта конечная точка

PDF4me Создать документ (один) Создает единый документ путем объединения шаблона (Word, HTML, или PDF) с полезной нагрузкой данных (JSON, XML, или CSV) в одном REST звонок. Шаблон может быть Base64, общественное URLили сырой HTMLДанные могут представлять собой встроенный текст, Base64закодированный файл или URLВозвращает отрендеренный результат. PDF, Docx, или HTML в двоичном виде (200) или через Location-заголовок опроса URL (202).

Похожие записи в блоге
Пока нет публикации в блоге, посвященной этой функции — она скоро появится.
А пока что, загляните в блог PDF4me, где вы найдете обучающие материалы и рабочие процессы для всех платформ.
Посетите блог →

Аутентификация вашего API Запрос​

Каждый PDF4me REST В звонке необходимо указать ваш API ключ в Authorization В заголовке используется базовая аутентификация. Получите или измените свой ключ на панели разработчика.

Конечная точка​

ПОЧТА/api/v2/GenerateDocumentSingle

Важные факты, которые нельзя пропустить​

Или documentDataText или documentDataFile
Необходимо указать ровно один источник данных, а не оба с соответствующим содержимым. Используйте documentDataText для встроенного JSON / XML / CSV. Использовать documentDataFile для Base64-закодированный файл данных или общедоступный URL.
Допустимый outputType зависит от templateFileType.
Docx, MailMerge, GoogleDocs принимают PDF или DocxHTML принимает HTML Только PDF. Принимаются PDF-файлы. PDF Только. Точный корпус имеет значение.
Асинхронный процесс возвращает 202 + заголовок Location
С 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Также требуется
T1Base64Base64 template file (strip data:...;base64, prefix if present)templateFileName
T2URLFull HTTPS URL string (not downloaded by the API request body)templateFileName
T3HTML codeBase64-encoded UTF-8 HTML: Buffer.from(html, "utf8").toString("base64")templateFileName, templateFileType: HTML

Данные документа (один из двух) API поля)​

КодИсточникполе APIЦенность почтальона
D1TextdocumentDataTextRaw JSON / XML / CSV string
D2Base64documentDataFileBase64 of the data file (strip data-URL prefix if present)
D3URLdocumentDataFileFull HTTPS URL to .json / .xml / .csv

Правило: ровно один из documentDataText или documentDataFile Необходимо установить значение. Неиспользуемое поле следует исключить из текста сообщения.

Распространенные комбинации​

#ШаблонДанныеТипичное использование
1T1 Docx base64D1 JSON textWord mail-merge to PDF
2T2 Docx URLD3 JSON URLHosted template + hosted data
3T3 HTMLD1 JSON textHTML mustache rendered to HTML / PDF
4T1 PDF formD2 JSON base64PDF template + encoded data file
5T2 MailMerge URLD1 XML textWord merge fields + inline XML

templateFileType → разрешенный outputType​

templateFileTypeДопустимый outputTypeПримечания
DocxPDF, DocxPDF4me Word template
MailMergePDF, DocxMail merge Word
GoogleDocsPDF, DocxGoogle Docs export style
HTMLHTML onlyMustache in HTML
PDFPDF onlyPDF form / template

API поля тела​

Всегда отправляется​

ПараметрНеобходимыйЧто это делаетПример
jobIdExtOptionalYour own reference for this call. It is stored with the API call log so you can correlate calls with your jobs. Type: string.
integrationsOptionalIntegration identifiers, forwarded unchanged with the job's notification settings. Type: array.
isAsyncOptionalSet 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
templateFileTypeOptionalType of the template file, e.g. `Docx`, `Html` or `Pdf`. Not used by GenerateDocumentSingleV2.Docx, HTML, PDF, MailMerge, GoogleDocs
templateFileDataOptionalRequired. 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
documentDataTypeOptionalFormat of the data, `Json`, `XML` or `Csv`.Json, XML, or Csv (exact casing)
templateFileNameOptionalRequired. 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
documentDataTextOptionalThe data as text. Used when `documentDataFile` is empty. Type: string.Valid JSON when documentDataType is Json; XML must look like XML; CSV non-empty
documentDataFileOptionalThe 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
outputTypeOptionalFormat of the generated document, e.g. `pdf` or `docx`. Not used by GenerateDocumentSingleV2.PDF, Docx, or HTML (see allowed-output table above)
metaDataJsonOptionalOptional document metadata as a JSON string. Type: string.
keepPdfEditableOptionalKeep 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",
"documentDataText": "name,email\nJohn Doe,[email protected]",
"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
}

Советы по сбору почты​

Body
Use raw JSON. The API does not accept form-data for this endpoint.
Base64 of data
For D2, base64-encode the whole .json / .xml / .csv file and put it in documentDataFile. Set documentDataType accordingly.
HTML template
For T3 in Postman: Buffer.from(html, "utf8").toString("base64"). Send the base64 in templateFileData with templateFileType: HTML.
Filename match
Match the extension in templateFileName to templateFileType: .docx for Word / MailMerge / GoogleDocs, .html for HTML, .pdf for PDF.
Save response
Save the response body as .pdf, .docx, or .html depending on outputType.

пример 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-файл
templateFileTypeReqReqReqReqReq
templateFileNameReqReqReqReqReq
templateFileDataReq (b64)Req (URL)Req (b64)Req (b64 HTML)Req
documentDataTypeReqReqReqReqReq
outputTypeReqReqReqReqReq
documentDataTextReqOmitOmitReqOmit
documentDataFileOmitReq (URL)Req (b64)OmitOmit
IsAsyncReqReqReqReqReq
KeepPdfEditableOptOptOptN/A*Opt if PDF

*KeepPdfEditable применяется только когда outputType является PDF; API В противном случае это ложно.

Примеры кода​

Часто задаваемые вопросы​

Can I send both documentDataText and documentDataFile in one request?+
No. Exactly one data source must be set. Omit the unused field. Sending both with content is rejected by the validation layer.
Which output types are allowed for each templateFileType?+
Docx, MailMerge, and GoogleDocs accept PDF or Docx. HTML accepts HTML only. PDF accepts PDF only. The casing of outputType matters.
Does KeepPdfEditable apply to every request?+
No. It only applies when outputType is PDF. For HTML or Docx output the API forces false and ignores the flag.
How do I send raw HTML in Postman?+
Base64-encode the UTF-8 HTML string (Buffer.from(html, "utf8").toString("base64") or the equivalent in your language). Put the result in templateFileData with templateFileType: HTML.
How do I encode the data file for D2?+
Base64-encode the entire .json, .xml, or .csv file bytes, not the parsed object. Put the base64 string in documentDataFile and set documentDataType to match.
How does the async flow work?+
Send IsAsync true. If the API returns 200, the rendered file is in the body. If 202, read the Location header for a poll URL. GET that URL with the same Authorization. Poll until 200.
My template Base64 has a data: prefix. Do I strip it?+
Yes. The API expects raw Base64 in templateFileData. Strip any data:...;base64, prefix before posting. Same applies to documentDataFile.
What extension should the response file have?+
Match outputType: .pdf for PDF, .docx for Docx, .html for HTML.

Связанные действия​

Аналогичная задача на других платформах.​

Создать документ (один) в Make
Визуальные сценарии, которые связывают шаблоны и источники данных в единую систему. REST конечная точка.
Создать документ (один) в Zapier
Запустите генерацию документа из любого из более чем 6000 источников. SaaS приложения и веб-хуки.
Создать документ (один) в Power Automate
Microsoft 365 потоки с SharePoint, OutlookИнтеграция с Teams и Dataverse.
Создать документ (один) в n8n
Самостоятельное размещение или облачное решение n8n рабочие процессы с одинаковым Base64 / URL / Двоичные режимы ввода.

Получить помощь​