How to Merge PDF Files in Business Central Using a Python API

 



When working with documents in Microsoft Dynamics 365 Business Central, sometimes we need to combine multiple PDF files into a single document — for example, when generating a bundle of invoices or reports.

In this post, I’ll show you how to achieve that by integrating Business Central AL code with a Python-based API using FastAPI and PyPDF2.


🐍 The Python API (FastAPI + PyPDF2)

We’ll expose a /merge-pdf endpoint using FastAPI that:

  • Accepts a list of PDFs encoded in Base64

  • Merges them using PyPDF2.PdfMerger

  • Returns the combined PDF as a Base64 string

Here’s the Python code:

python

from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel import base64 from PyPDF2 import PdfMerger from io import BytesIO app = FastAPI() class PDFRequest(BaseModel): archivos_pdf: list[str] # List of Base64 PDF files class PDFResponse(BaseModel): pdf_unido: str # Base64-encoded merged PDF API_KEY = "YourApiKey" @app.post("/merge-pdf", response_model=PDFResponse) async def unir_pdf(data: PDFRequest, x_api_key: str = Header(None)): if x_api_key != API_KEY: raise HTTPException(status_code=401, detail="Unauthorized access") merger = PdfMerger() for archivo_base64 in data.archivos_pdf: archivo_pdf = BytesIO(base64.b64decode(archivo_base64)) merger.append(archivo_pdf) pdf_unido_io = BytesIO() merger.write(pdf_unido_io) merger.close() pdf_unido_io.seek(0) return PDFResponse(pdf_unido=base64.b64encode(pdf_unido_io.read()).decode('utf-8'))

⚙️ The AL Code in Business Central

Here’s the AL codeunit that sends the list of PDF Base64 strings to the Python API:

al

codeunit 50149 MergePDF { procedure MergePdfAPI(PDFsBase64: List of [Text]) PDFUnidoBase64: Text var Client: HttpClient; RequestMsg: HttpRequestMessage; ResponseMsg: HttpResponseMessage; Content: HttpContent; JsonRequest: JsonObject; JsonArrayPDFs: JsonArray; JsonResponse: JsonObject; JsonToken: JsonToken; ResponseText: Text; Url: Text; I: Integer; JsonText: Text; Headers: HttpHeaders; RequestHeaders: HttpHeaders; begin Url := 'http://"YourIPAddress":YourPort/merge-pdf'; Clear(JsonRequest); Clear(JsonArrayPDFs); for I := 1 to PDFsBase64.Count() do JsonArrayPDFs.Add(PDFsBase64.Get(I)); JsonRequest.Add('archivos_pdf', JsonArrayPDFs); JsonRequest.WriteTo(JsonText); Content.WriteFrom(JsonText); Content.GetHeaders(Headers); Headers.Clear(); Headers.Add('Content-Type', 'application/json'); RequestMsg.Method('POST'); RequestMsg.SetRequestUri(Url); RequestMsg.Content(Content); RequestMsg.GetHeaders(RequestHeaders); RequestHeaders.Add('x-api-key', 'YourApiKey'); // API Key if Client.Send(RequestMsg, ResponseMsg) then begin ResponseMsg.Content().ReadAs(ResponseText); if ResponseMsg.IsSuccessStatusCode() then begin JsonResponse.ReadFrom(ResponseText); if JsonResponse.Get('pdf_unido', JsonToken) then PDFUnidoBase64 := JsonToken.AsValue().AsText() else Error('No merged PDF received.'); end else Error('API Error: %1', ResponseText); end else Error('Connection to API failed.'); end; }

✅ Benefits of This Integration

  • No need for third-party components inside Business Central

  • Flexible — works with any external Python service

  • Easy to deploy and extend

Comentarios

Entradas populares de este blog

Join two or more PDFs into one in Business Central

How to Print Multiple Copies in Report in AL of Microsoft Dynamics 365 Business Central