Saltar al contenido principal

Generar documento (único)

Lo que hace este punto final

PDF4me Generar documento (único) genera un único documento mediante la fusión de una plantilla (Word, HTML, o PDF) con una carga útil de datos (JSON, XML, o CSV) en uno REST llamar. La plantilla puede ser Base64, un público URLo crudo HTML. Los datos pueden ser texto en línea, un Base64archivo codificado o un URL. Devuelve el renderizado PDF, Documento, o HTML como binario (200) o a través de un Location-encuesta de encabezado URL (202).

Entradas de blog relacionadas
Aún no hay ninguna entrada de blog sobre esta función; estará disponible próximamente.
Mientras tanto, echa un vistazo al blog de PDF4me para encontrar tutoriales y flujos de trabajo para todas las plataformas.
Visita el blog

Autenticando su API Pedido

Cada PDF4me REST La llamada debe incluir su API clave en el Authorization Encabezado como autenticación básica. Obtenga o cambie su clave desde el panel de desarrollador.

Punto final

CORREO/api/v2/GenerateDocumentSingle

Datos importantes que no debes perderte

Cualquiera textoDatosDocumento o archivo de datos del documento
Se debe configurar exactamente una fuente de datos, no ambas con contenido. textoDatosDocumento para en línea JSON / XML / CSV. Usar archivo de datos del documento por un Base64archivo de datos codificado o un archivo público URL.
El tipo de salida permitido depende del tipo de archivo de plantilla.
Se aceptan archivos Docx, MailMerge y Google Docs. PDF o Documento. HTML acepta HTML solamente. PDF acepta PDF solamente. El tipo de carcasa exacto importa.
Async devuelve 202 + encabezado Location
Con IsAsync: true el API puede responder 202 y un encabezado Location. GET eso URL (misma autorización) hasta 200 con el archivo renderizado (estándar) pdf4meAsyncRequest patrón).

HTTP configuración

Método: CORREO
URL: https://api.pdf4me.com/api/v2/GenerateDocumentSingle
Tipo de contenido: aplicación/json
Autorización: Básico <tu PDF4me API clave>

Enviar IsAsync: true en el cuerpo. 200 Devuelve los bytes del archivo renderizado. 202 devuelve un Ubicación encabezado con una encuesta URL; GET eso URL con el mismo encabezado de autorización hasta 200.

Matriz de variantes (relevante para Postman)

Seleccione una variante de plantilla (T1 / T2 / T3) y una variante de datos (D1 / D2 / D3). Seis combinaciones cubren todas las llamadas.

Plantilla (templateFileData)

CódigoFuenteValor del cartero en datos de archivo de plantillaTambién se requiere
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

Datos del documento (uno de dos API campos)

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

Regla: exactamente uno de textoDatosDocumento o archivo de datos del documento Debe configurarse. Omita el campo no utilizado del cuerpo.

Combinaciones comunes

#PlantillaDatosUso 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 → allowed outputType

tipoArchivoDePlantillaPermitido tipo de salidaNotas
DocxPDF, DocxPDF4me Word template
MailMergePDF, DocxMail merge Word
GoogleDocsPDF, DocxGoogle Docs export style
HTMLHTML onlyMustache in HTML
PDFPDF onlyPDF form / template

API campos corporales

Siempre enviado

CampoRequeridoTipoNotas
templateFileTypeYesstringDocx, HTML, PDF, MailMerge, GoogleDocs
templateFileNameYesstringWith extension, e.g. template.docx, template.html, template.pdf
templateFileDataYesstringBase64 template, or template URL string
documentDataTypeYesstringJson, XML, or Csv (exact casing)
outputTypeYesstringPDF, Docx, or HTML (see allowed-output table above)
IsAsyncYesbooleantrue

Datos del documento (una ruta)

CampoRequerido cuandoTipoNotas
documentDataTextD1 (text)stringValid JSON when documentDataType is Json; XML must look like XML; CSV non-empty
documentDataFileD2 or D3stringBase64 data file or URL to data file

Opcional

CampoCuandoPor defecto
KeepPdfEditableoutputType is PDFfalse
documentDataFileD1 text path is usedOmitted
documentDataTextD2 or D3 path is usedOmitted

Reglas de validación

ControlarDetalle
Template URLNon-empty, valid URL.
Template base64Non-empty after optional data-URL strip.
HTML codeOnly when templateFileType is HTML. Empty is rejected. Auto-wraps <html> if missing.
JSON textMust parse successfully with JSON.parse.
XML textMust start with < and contain >.
CSV textNon-empty after trim.
Either data sourcedocumentDataFile or documentDataText is required.

Ejemplos de marcador de posición

ArtículoEjemplo
Template URL (Docx)https://example.com/template.docx
Template nametemplate.docx / template.html / template.pdf
Data URL (JSON)https://example.com/data.json
Data file namedata.json
JSON text{"name": "John Doe", "email": "[email protected]", "items": [{"product": "Widget", "price": 29.99}]}
XML text<?xml version="1.0"?><root><name>John Doe</name></root>
CSV textname,email\nJohn Doe,[email protected]
HTML template<!DOCTYPE html>...{{title}}...

Cargas útiles de ejemplo

1. Plantilla de 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. Plantilla de Word (URL) + JSON datos (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. Plantilla de Word (base64) + JSON datos (base64) → Salida de palabras

documentDataFile contiene base64 de la JSON bytes del archivo (no el objeto analizado).

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

4. HTML plantilla (base64 de HTML archivo) + JSON texto → HTML

Para crudo HTML en Postman, envíe la misma carga útil n8n El nodo sería: codificado en base64 HTML en templateFileData.

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

5. Combinación de correspondencia (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 Plantilla de formulario (base64) + CSV texto → PDF (editable)

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

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

Consejos para el cobro de carteros

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.

Ejemplo 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

Referencia rápida: obligatorio vs. opcional por variante

CampoT1+D1T2+D3T1+D2T3+D1Cualquier PDF fuera
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

*Conservar PDF editable solo se aplica cuando tipo de salida es PDF; el API fuerzas falsas de otro modo.

Ejemplos de código

Preguntas frecuentes

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.

Acciones relacionadas

La misma tarea en otras plataformas.

Obtén ayuda