[Django]-How to add images to a Pdf file from static files using borb library and Django

4👍

Disclaimer: I am Joris Schellekens, author of aforementioned library borb.

The constructor of Image either accepts:

  • a str if you intend to grab the image from a URL
  • a Path if you intend to use a local image on your filesystem

You specified a str so borb is under the impression you want to use a file that is present on your filesystem.

It then tries to assert whether that file exists. Which is not the case. Hence the error.

The solution would be to either provide a Path or the fully resolved file-path as a str.

4👍

Just to complement the Answer, Joris Schellekens, we need to pass a type(Path) object, not a type(str), in order borb to "understand" it is a local file.

You can see this other questions to see how to convert str to Path but I summarize below a full example based on this article also from Joris although with some changes to correct failures I had running it (pdf.add_page(page) instead of pdf.append_page(page), and from borb.pdf import Document instead of from borb.pdf.document import Document).

Of course in the code, change the path to your logo and the size you need, etc.):

import os
from pathlib import Path
from decimal import Decimal 
# import third party libraries:
from borb.pdf import Document
from borb.pdf.page.page import Page
from borb.pdf.canvas.layout.page_layout.multi_column_layout import SingleColumnLayout
from borb.pdf.canvas.layout.image.image import Image
from borb.pdf.pdf import PDF

# NOTICE BELOW THE TYPE IS CONVERTED TO Path using pathlib
IMAGE_PATH = Path(r"C:\Users\...\image.png") #change to fit your path

def create_pdf (pdf_filename , outp_folder):
    os.makedirs(outp_folder, exist_ok=True)
    pdf_filepath = os.path.join(outp_folder, pdf_filename + ".pdf")
    pdf = Document()
    page = Page()
    pdf.add_page(page)
    page_layout = SingleColumnLayout(page)
    page_layout.vertical_margin = page.get_page_info().get_height() *     Decimal(0.02)
    page_layout.add(
         Image(image=IMAGE_PATH, width=100, height=100)) #change the size as you wish
    LayoutElement = Image
    with open(pdf_filepath, "wb") as pdf_file_handle:
        PDF.dumps(pdf_file_handle, pdf)


if __name__ == "__main__":
    ##### DECLARE CONSTANTS FOR THE TEST CODE
    TEST_FILE_NAME = "your_file_name.pdf" #here would go the name of your pdf file
    TEST_OUTP_FOLDER = "your_output_folder"
    create_pdf(pdf_filename = TEST_FILE_NAME, outp_folder = TEST_OUTP_FOLDER)

Leave a comment