Label fixed width AND height

Skip Navigation LinksHome  /  Support  /  Forums  /  DynamicPDF CoreSuite for .NET (v12)  /  Label fixed width AND height

DynamicPDF CoreSuite for .NET (v12) Forum

 May 20 2024 9:46 AM
Hello,

I am trying to put a label on a PDF document such that the width and the height needs to be respected. The label being stretched or cropped out is not an issue and the font size can be dynamic.

I have found an article to set the font size dynamically based on the width of the label but the height is not respected.

Can you help?

Thanks,
Nizar
 Jun 07 2024 12:55 AM
Hey there,
After reading your query i understood that  you need to add a label to a PDF document with specific width and height constraints, and that you're okay with the label being stretched or cropped as long as the font size is dynamic. So, what you can do is to add a label to a PDF with fixed width and height using Python you have to follow these steps:
1) Install' reportlab'
pip install reportlab
2Use this script:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def draw_label(canvas, text, x, y, width, height):
    font_name = "Helvetica"
    font_size = 1
    while True:
        canvas.setFont(font_name, font_size)
        if canvas.stringWidth(text, font_name, font_size) > width or font_size > height:
            break
        font_size += 1
    font_size -= 1
    canvas.setFont(font_name, font_size)
    canvas.drawString(x, y + height - font_size, text)

def create_pdf(file_path, text, x, y, width, height):
    c = canvas.Canvas(file_path, pagesize=letter)
    draw_label(c, text, x, y, width, height)
    c.save()

# Example usage
create_pdf("output.pdf", "This is a test label", 100, 700, 200, 50)

HOPE IT HELPS YOU!!

All times are US Eastern Standard time. The time now is 12:58 AM.