Pular para o conteúdo principal

Gerar documento (único)

O que este endpoint faz

PDF4me Gerar documento (único) gera um único documento mesclando um modelo (Word, HTML, ou PDF) com uma carga útil de dados (JSON, XML, ou CSV) em um REST chamada. O modelo pode ser Base64, um público URLou cru HTMLOs dados podem ser texto embutido, um Base64arquivo codificado, ou um URLRetorna o resultado renderizado. PDF, Docx, ou HTML como binário (200) ou via um Location-cabeçalho da pesquisa URL (202).

Artigos relacionados no blogue
Ainda não há nenhuma publicação no blogue sobre esta funcionalidade — em breve.
Entretanto, explore o blogue da PDF4me para encontrar tutoriais e fluxos de trabalho para todas as plataformas.
Visite o blogue →

Autenticando seu API Solicitar​

Todo PDF4me REST A chamada deve incluir o seu API chave no Authorization Defina o cabeçalho como autenticação básica. Obtenha ou altere sua chave no painel do desenvolvedor.

Ponto final​

PUBLICAR/api/v2/GenerateDocumentSingle

Fatos importantes que você não deve perder​

Qualquer textoDoDocumento ou arquivo de dados do documento
É necessário definir apenas uma fonte de dados, e não ambas com conteúdo. Use textoDoDocumento para em linha JSON / XML / CSV. Usar arquivo de dados do documento para um Base64-arquivo de dados codificado ou um público URL.
O tipo de saída permitido depende do tipo de arquivo de modelo.
Docx, MailMerge e Google Docs aceitam PDF ou DocxO HTML aceita HTML Somente PDF. Aceita PDF Apenas. A grafia exata das letras maiúsculas e minúsculas é importante.
Async retorna 202 + cabeçalho Location
Com IsAsync: verdadeiro o API Pode responder com o código 202 e um cabeçalho de localização. GET que URL (mesma autorização) até 200 com o arquivo renderizado (padrão) pdf4meAsyncRequest padrão).

HTTP configurar​

Método: PUBLICAR
URL: https://api.pdf4me.com/api/v2/GenerateDocumentSingle
Tipo de conteúdo: aplicativo/json
Autorização: Básico <seu PDF4me API chave>

Enviar IsAsync: verdadeiro no corpo. 200 Retorna os bytes do arquivo renderizado. 202 retorna um Localização cabeçalho com uma enquete URL; GET que URL com o mesmo cabeçalho de autorização até 200.

Matriz variante (relevante para o Postman)​

Selecione uma variante de modelo (T1 / T2 / T3) e uma variante de dados (D1 / D2 / D3). Seis combinações abrangem todas as chamadas.

Modelo (templateFileData)​

CódigoFonteValor do carteiro em dados do arquivo de modeloTambém necessário
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

Dados do documento (um de dois) API campos)​

CódigoFonteCampo da APIValor do carteiro
D1TextdocumentDataTextRaw JSON / XML / CSV string
D2Base64documentDataFileBase64 of the data file (strip data-URL prefix if present)
D3URLdocumentDataFileFull HTTPS URL to .json / .xml / .csv

Regra: exatamente um de textoDoDocumento ou arquivo de dados do documento Deve ser definido. Omita o campo não utilizado do corpo.

Combinações comuns​

#ModeloDadosUso típico
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 → tipo de saída permitido​

tipoDeArquivoDeModeloPermitido tipo de saídaNotas
DocxPDF, DocxPDF4me Word template
MailMergePDF, DocxMail merge Word
GoogleDocsPDF, DocxGoogle Docs export style
HTMLHTML onlyMustache in HTML
PDFPDF onlyPDF form / template

API campos corporais​

Sempre enviado​

ParâmetroObrigatórioO que fazExemplo
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

Exemplos de cargas úteis​

1. Modelo do Word (base64) + JSON texto → 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. Modelo do Word (URL) + JSON dados (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. Modelo do Word (base64) + JSON dados (base64) → Saída em formato de palavra​

documentDataFile contém base64 do JSON bytes do arquivo (não o objeto analisado).

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

4. HTML modelo (base64 de HTML arquivo) + JSON texto → HTML​

Para cru HTML No Postman, envie a mesma carga útil. n8n O nó faria: codificado em base64 HTML em templateFileData.

{
"templateFileType": "HTML",
"templateFileName": "template.html",
"templateFileData": "PCFET0NUWVBFIGh0bWw+...",
"documentDataType": "Json",
"documentDataText": "{\"title\": \"Invoice\", \"heading\": \"Hello\", \"content\": \"World\"}",
"outputType": "HTML",
"IsAsync": true
}

5. Mala direta (URL) + XML texto → 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 Modelo de formulário (base64) + CSV texto → PDF (editável)​

{
"templateFileType": "PDF",
"templateFileName": "template.pdf",
"templateFileData": "JVBERi0xLjQKJcfsj6IK...",
"documentDataType": "Csv",
"documentDataText": "name,email\nJohn Doe,[email protected]",
"outputType": "PDF",
"KeepPdfEditable": true,
"IsAsync": true
}

7. Estilo do 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
}

Dicas de coleta do carteiro​

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.

exemplo de 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

Referência rápida: obrigatório vs. opcional por variante​

CampoT1+D1T2+D3T1+D2T3+D1Qualquer PDF fora
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

*ManterPdfEditável só se aplica quando tipo de saída é PDF; o API força falso caso contrário.

Exemplos de código​

Perguntas frequentes​

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.

Ações relacionadas​

A mesma tarefa em outras plataformas.​

Obtenha ajuda​