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

Создание документов (нескольких)

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

PDF4me Создание документов (нескольких) отображает множество документов в одном месте REST Позвоните. Отправьте одно слово. HTML, или PDF шаблон (Base64, URLили сырой HTML) плюс массив записей (JSON или XMLв виде текста, Base64 файл или URL). Возвращает a JSON список сгенерированных файлов (одна запись на каждую запись) в виде Base64 в outputDocuments[].streamFileили один бинарный результат в зависимости от ответа.

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

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

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

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

ПОЧТА/api/v2/GenerateDocumentMultiple

Название конечной точки: GenerateDocumentMultiple (единственное число) Документ), нет Создать несколько документов.

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

Один шаблон, множество записей
Отправить JSON массив (или повторяющаяся запись) XML) в ваших данных. Движок генерирует один выходной документ для каждого элемента массива и возвращает их вместе.
Ответ обычно JSON outputDocuments[]
Каждая запись имеет имя файла и base64 streamFile (иногда fileContent, содержание, или данныеРасшифруйте каждую строку base64, чтобы сохранить файл.
Отличия от Single: не поддерживаются CSV-файлы, разрешены xlsx-файлы, меньше типов шаблонов.
Ограничение типов шаблонов Docx, HTML, PDFТипы данных ограничены Джсон, XML. Вывод добавляет xlsx для Word / PDF шаблоны.

HTTP настраивать​

Метод: ПОЧТА
URL: https://api.pdf4me.com/api/v2/GenerateDocumentMultiple
Content-Type: приложение/json
Авторизация: Базовый <ваш PDF4me API ключ>

Отправлять IsAsync: true в организме. 200 может вернуться JSON с outputDocuments[] или один бинарный файл. 202 возвращает Расположение заголовок с опросом URL.

Различия между функцией «Создать документ (один)» и функцией «Создать документ (один)»​

ТемаНесколькоОдинокий
Endpoint/api/v2/GenerateDocumentMultiple/api/v2/GenerateDocumentSingle
templateFileTypeDocx, HTML, PDF onlyAlso MailMerge, GoogleDocs
documentDataTypeJson, XML onlyAlso Csv
outputTypePDF, Docx, xlsx (Word/PDF), HTMLNo xlsx
Data shapeTypically array of records (one doc per row)Usually one object
outputFileNameIntegration-UI only (output naming)Not in API body either

Матрица вариантов (применимо к Postman)​

Шаблон (templateFileData)​

КодИсточникЦенность почтальонаТакже требуется
T1Base64Base64 template (strip data:...;base64, prefix if present)templateFileName
T2URLHTTPS URL stringtemplateFileName
T3HTML codeBase64(UTF-8 HTML): Buffer.from(html, "utf8").toString("base64")templateFileName, templateFileType: HTML

Данные документа​

КодИсточникполе APIЦенность почтальона
D1TextdocumentDataTextJSON array (or XML with multiple records)
D2Base64documentDataFileBase64 of the .json / .xml file
D3URLdocumentDataFileURL to the data file

Используйте любой из вариантов documentDataText или documentDataFile (неиспользуемое поле следует опустить).

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

templateFileTypeДопустимый outputType
DocxPDF, Docx, xlsx
PDFPDF, Docx, xlsx
HTMLHTML only

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
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
documentDataTypeOptionalFormat of the data, `Json`, `XML` or `Csv`.Json or XML (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.e.g. template.docx, template.html, template.pdf
documentDataTextOptionalThe data as text. Used when `documentDataFile` is empty. Type: string.Valid JSON (JSON.parse) or XML-like for XML
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
outputTypeOptionalFormat of the generated document, e.g. `pdf` or `docx`. Not used by GenerateDocumentSingleV2.PDF, Docx, xlsx, or HTML
metaDataJsonOptionalOptional document metadata as a JSON string. Type: string.
keepPdfEditableOptionalKeep form fields editable when the output is a PDF. Type: boolean.false

Форма данных, состоящая из нескольких записей​

Для JSONИспользуйте массив объектов (один объект на каждый сгенерированный документ):

[
{ "name": "Alice", "email": "[email protected]" },
{ "name": "Bob", "email": "[email protected]" }
]

Для XMLИспользуйте структуру, которую ожидает ваш шаблон для повторяющихся строк (та же идея, что и при слиянии почты). API проверяет только это JSON Процесс парсинга определяет количество создаваемых документов.

API ответ (Почтальон)​

Часто используется формат JSON:

{
"outputDocuments": [
{
"fileName": "document1.pdf",
"streamFile": "<base64>"
}
]
}

Название поля также может отображаться как fileContent, content, или dataРасшифруйте каждый Base64 строка для сохранения каждого файла.

Примеры полезных нагрузок​

1. Шаблон Word (base64) + JSON массив (текст) → множественный PDFs​

{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "Json",
"documentDataText": "[{\"name\": \"Alice\", \"email\": \"[email protected]\"}, {\"name\": \"Bob\", \"email\": \"[email protected]\"}]",
"outputType": "PDF",
"KeepPdfEditable": false,
"IsAsync": true
}

2. Шаблон Word (URL) + JSON данные (URL) → PDFs​

{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "https://example.com/template.docx",
"documentDataType": "Json",
"documentDataFile": "https://example.com/customers.json",
"outputType": "PDF",
"IsAsync": true
}

3. Шаблон Word (base64) + JSON файл (base64) → Excel (xlsx)​

{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "Json",
"documentDataFile": "W3sibmFtZSI6ICJBbGljZSJ9LCB7Im5hbWUiOiAiQm9iIn1d",
"outputType": "xlsx",
"IsAsync": true
}

(documentDataFile = основание 64 [{"name":"Alice"},{"name":"Bob"}].)

4. HTML шаблон (base64) + JSON массив (текст) → HTML​

{
"templateFileType": "HTML",
"templateFileName": "template.html",
"templateFileData": "PCFET0NUWVBFIGh0bWw+...",
"documentDataType": "Json",
"documentDataText": "[{\"title\": \"Invoice 1\", \"heading\": \"Hello\", \"content\": \"A\"}, {\"title\": \"Invoice 2\", \"heading\": \"Hi\", \"content\": \"B\"}]",
"outputType": "HTML",
"IsAsync": true
}

5. PDF шаблон (URL) + XML (текст) → множественный PDFs​

{
"templateFileType": "PDF",
"templateFileName": "template.pdf",
"templateFileData": "https://example.com/template.pdf",
"documentDataType": "XML",
"documentDataText": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><name>Alice</name></record><record><name>Bob</name></record></records>",
"outputType": "PDF",
"KeepPdfEditable": true,
"IsAsync": true
}

6. Шаблон Word (base64) + XML (URL) → Word (Docx)​

{
"templateFileType": "Docx",
"templateFileName": "template.docx",
"templateFileData": "UEsDBBQAAAAI...",
"documentDataType": "XML",
"documentDataFile": "https://example.com/data.xml",
"outputType": "Docx",
"IsAsync": true
}

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

Array data
Prefer a JSON array in documentDataText when documentDataType is Json and you expect more than one file.
Filename match
Match the extension in templateFileName to templateFileType.
Base64 of file
For D2, base64-encode the whole data file (not each row separately).
Decode response
If the response is JSON, decode each outputDocuments[].streamFile (or fileContent / content / data) from base64.
Endpoint name
Endpoint name is GenerateDocumentMultiple (singular Document), not GenerateDocumentsMultiple.

пример curl​

curl -X POST https://api.pdf4me.com/api/v2/GenerateDocumentMultiple \
-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",
"documentDataText": "[{\"name\":\"Alice\"},{\"name\":\"Bob\"}]",
"outputType": "PDF",
"IsAsync": true
}' \
--output response.json

Краткий справочник: обязательные и необязательные опции в зависимости от варианта​

ПолеТ1+Д1Т2+Д3Т1+Д2Т3+Д1вывод в формате PDF
templateFileTypeReqReqReqReqReq
templateFileNameReqReqReqReqReq
templateFileDataReq (b64)Req (URL)Req (b64)Req (b64)Req
documentDataTypeReqReqReqReqReq
outputTypeReqReqReqReqReq
documentDataTextReqOmitOmitReqOmit
documentDataFileOmitReqReqOmitOmit
IsAsyncReqReqReqReqReq
KeepPdfEditableOptOptOptN/A*Opt

*Только когда outputType является PDF.

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

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

How is Multiple different from Single?+
Different endpoint (/api/v2/GenerateDocumentMultiple), fewer template types (Docx, HTML, PDF only), no CSV, can output xlsx, and expects array-shaped data to produce one document per record in a single call.
What does the response look like?+
Typically a JSON object with outputDocuments[], each containing fileName and streamFile (base64). Some responses may use fileContent, content, or data as the field name. Decode each base64 string to save the file.
Which output types are allowed?+
Docx and PDF templates accept PDF, Docx, or xlsx. HTML template accepts HTML only.
Does HTML output produce multiple files?+
Yes when the engine renders one HTML document per input record. The response still uses the outputDocuments[] shape.
What is the maximum array size?+
No published hard cap. Large batches usually push you onto the async path (202 + Location poll). For very large workloads, split into multiple calls of a few hundred records each.
Why is the endpoint name singular Document?+
The path is /api/v2/GenerateDocumentMultiple, not GenerateDocumentsMultiple. A common typo. The plural version returns 404.
Does KeepPdfEditable work for xlsx or HTML output?+
No. It only applies when outputType is PDF. For other outputs the API ignores it.
Can I mix multiple template files in one call?+
No. One call uses one template. To render the same data set against multiple templates, issue one call per template.

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

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

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