Создание документов (нескольких)
PDF4me Создание документов (нескольких) отображает множество документов в одном месте REST Позвоните. Отправьте одно слово. HTML, или PDF шаблон (Base64, URLили сырой HTML) плюс массив записей (JSON или XMLв виде текста, Base64 файл или URL). Возвращает a JSON список сгенерированных файлов (одна запись на каждую запись) в виде Base64 в outputDocuments[].streamFileили один бинарный результат в зависимости от ответа.
Аутентификация вашего API Запрос
Каждый PDF4me REST В звонке необходимо указать ваш API ключ в Authorization В заголовке используется базовая аутентификация. Получите или измените свой ключ на панели разработчика.
Конечная точка
/api/v2/GenerateDocumentMultipleНазвание конечной точки: GenerateDocumentMultiple (единственное число) Документ), нет Создать несколько документов.
Важные факты, которые нельзя пропустить
outputDocuments[]имя файла и base64 streamFile (иногда fileContent, содержание, или данныеРасшифруйте каждую строку base64, чтобы сохранить файл.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 |
| templateFileType | Docx, HTML, PDF only | Also MailMerge, GoogleDocs |
| documentDataType | Json, XML only | Also Csv |
| outputType | PDF, Docx, xlsx (Word/PDF), HTML | No xlsx |
| Data shape | Typically array of records (one doc per row) | Usually one object |
| outputFileName | Integration-UI only (output naming) | Not in API body either |
Матрица вариантов (применимо к Postman)
Шаблон (templateFileData)
| Код | Источник | Ценность почтальона | Также требуется |
|---|---|---|---|
| T1 | Base64 | Base64 template (strip data:...;base64, prefix if present) | templateFileName |
| T2 | URL | HTTPS URL string | templateFileName |
| T3 | HTML code | Base64(UTF-8 HTML): Buffer.from(html, "utf8").toString("base64") | templateFileName, templateFileType: HTML |
Данные документа
| Код | Источник | поле API | Ценность почтальона |
|---|---|---|---|
| D1 | Text | documentDataText | JSON array (or XML with multiple records) |
| D2 | Base64 | documentDataFile | Base64 of the .json / .xml file |
| D3 | URL | documentDataFile | URL to the data file |
Используйте любой из вариантов documentDataText или documentDataFile (неиспользуемое поле следует опустить).
templateFileType → разрешенный outputType
templateFileType | Допустимый outputType |
|---|---|
Docx | PDF, Docx, xlsx |
PDF | PDF, Docx, xlsx |
HTML | HTML only |
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 |
| 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 |
| documentDataType | Optional | Format of the data, `Json`, `XML` or `Csv`. | Json or XML (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. | e.g. template.docx, template.html, template.pdf |
| documentDataText | Optional | The data as text. Used when `documentDataFile` is empty. Type: string. | Valid JSON (JSON.parse) or XML-like for XML |
| 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 |
| outputType | Optional | Format of the generated document, e.g. `pdf` or `docx`. Not used by GenerateDocumentSingleV2. | PDF, Docx, xlsx, or HTML |
| 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 |
Форма данных, состоящая из нескольких записей
Для JSONИспользуйте массив объектов (один объект на каждый сгенерированный документ):
[
]
Для 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
}
Советы по сбору почты
пример 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 |
|---|---|---|---|---|---|
templateFileType | Req | Req | Req | Req | Req |
templateFileName | Req | Req | Req | Req | Req |
templateFileData | Req (b64) | Req (URL) | Req (b64) | Req (b64) | Req |
documentDataType | Req | Req | Req | Req | Req |
outputType | Req | Req | Req | Req | Req |
documentDataText | Req | Omit | Omit | Req | Omit |
documentDataFile | Omit | Req | Req | Omit | Omit |
IsAsync | Req | Req | Req | Req | Req |
KeepPdfEditable | Opt | Opt | Opt | N/A* | Opt |
*Только когда outputType является PDF.