Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add Chinese watermarks to PDF files in batches by Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian introduces in detail for you "Python how to add Chinese watermarks to PDF files in batches" with detailed contents, clear steps and proper handling of details. I hope that this article "Python how to add Chinese watermarks to PDF files in batches" can help you solve your doubts.

Preface

You can add PDF watermarks in batches by setting the path where the batch PDF files are located and the name of the watermark to be added.

The idea is to generate a watermarked PDF template under the path of the batch PDF file. Finally, each PDF page of the batch file and the watermark template are merged to complete the effect of adding watermarks in batches.

It should be noted that batch PDF files must be the same size as the PDF template watermark file, which can be adjusted in the code.

Implementation steps

First of all, prepare the PDF file that needs to be watermarked and put it under a folder.

Set the path and watermark name of PDF batch files in the code.

If _ _ name__ = ='_ _ main__': main ('C _ main__': main','I am a watermark')

The internal implementation process is encapsulated in the main () function. Here, just change the watermark name and the path of the batch PDF file to execute directly.

After startup, the following results indicate that the execution has been completed.

In order not to overwrite the original PDF file, the merged files are all PDF files with the word "merged" added.

When you're done, take a look at the main code blocks.

The third-party libraries used are the following, in which I wrote relevant comments.

Import os # Application File manipulation # reportlab is a standard library of Python, which can draw pictures, draw tables, edit text, and finally export PDF format. The main function of from reportlab.pdfgen import canvasfrom reportlab.lib.units import cmfrom reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontpdfmetrics.registerFont (TTFont ('songti',' Cvolux PyPDF2)) # load Arial # is to split or merge PDF files, cut or convert pages in Windows files From PyPDF2 import PdfFileWriter, PdfFileReaderimport logging # Log print Library

The initialization of the log module is also relatively simple, and there have been related calls in previous articles.

# initialization log settings logger = logging.getLogger ('batch watermarking') logging.basicConfig (format='% (asctime) s% (levelname)-8s:% (message) s') logger.setLevel (logging.DEBUG)

After the log initialization is completed, you can call it later where you need to print the log.

There are three main functions in the implementation process, one is to generate the watermark template, the other is to merge the watermark template and batch PDF files to realize the function of adding watermark, and the other is to traverse the batch PDF files one by one so that they can merge watermarks one by one.

Watermark template generation function.

Def generate_water_pdf (content):''generate PDF with watermark: param content: watermark name: return:' 'cans = canvas.Canvas (' water_back.pdf', pagesize= (21 * cm, 29.7 * cm)) cans.translate (10 * cm, 12 * cm) # move origin coordinates cans.setFont ('songti' 23) # set font to Song style, size 23 cans.setFillColorRGB (0.5,0.5,0.5) # set font background color cans.rotate (45) # set font tilt 45 degrees cans.drawString (- 7 * cm, 0 * cm, content) cans.drawString (7 * cm, 0 * cm, content) cans.drawString (0 * cm, 7 * cm Content) cans.drawString (0 * cm,-7 * cm, content) cans.save () # PDF file that saves the watermark

Watermark synthesis to achieve the function.

Def insert_water_to_pdf (input_pdf, output_pdf Water_pdf):''merge watermark into PDF file: param input_pdf: input file path: param output_pdf: output file path: param water_pdf: watermark file path: return:' 'water = PdfFileReader (water_pdf) # read watermark PDF water_page = water.getPage (0) # get the first page of watermark PDF pdf = PdfFileReader (input_pdf Strict=False) # read the file that needs to be watermarked pdf_writer = PdfFileWriter () # create the PDF file write object for page in range (pdf.getNumPages ()): # iterate through each page PDF object pdf_page = pdf.getPage (page) # get PDF's current page object pdf_page.mergePage (water_page) # merge the watermark page into the current page Pdf_writer.addPage (pdf_page) # adds the merged PDF object page to the PDF write object output_file = open (output_pdf 'wb') # Open the PDF output file pdf_writer.write (output_file) # write the file to the output file output_file.close () # close the write stream

The batch PDF file traversal calls the composite function.

Def main (diretory, current): if os.path.isdir (diretory): logger.info ('folder [' + diretory +'] verified successfully!) Os.chdir (diretory) logger.info ('current path is [' + os.getcwd () +']') generate_water_pdf (current) logger.info ('watermark PDF file generated successfully!') For file_path, dir_names File_names in os.walk (ringing'+ os.getcwd ()): for file_name in file_names: try: name = file_name.split ('.') [0] if name = = 'water_back': continue else: File_name_path = os.path.join (file_path File_name) output_file_path = file_name_path.split ('.') [0] +'_ added watermark .pdf 'insert_water_to_pdf (file_name_path, output_file_path,' water_back.pdf') logger.info ('['+ file_name_path +'] complete watermark merge!') Except Exception as e: logger.error ('['+ file_name_path +'] exception occurs, execute next!) Logger.error ('exception message:' + repr (e)) else: logger.info ('folder [' + diretory +'] failed to verify!)

The main implementation process is completed through the above three functions, and finally call the background entry function to call the mian () function to execute.

The complete code #-*-coding:utf-8-*-# @ author Python concentration Camp # @ date 2022 import os 27# @ file test4.py# done# adds Chinese watermarks to PDF files in batches. Import os # Application File Operation # reportlab is a standard library of Python, which can draw pictures, draw tables, edit text, and finally export PDF format. The main function of from reportlab.pdfgen import canvasfrom reportlab.lib.units import cmfrom reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontpdfmetrics.registerFont (TTFont ('songti',' Cvolux PyPDF2)) # load Arial # is to split or merge PDF files, cut or convert pages in Windows files From PyPDF2 import PdfFileWriter PdfFileReaderimport logging # Log print Library # initialize log settings logger = logging.getLogger ('batch watermark') logging.basicConfig (format='% (asctime) s% (levelname)-8s:% (message) s') logger.setLevel (logging.DEBUG) def generate_water_pdf (content):''generate PDF: param content: watermark name: return:' 'cans = canvas.Canvas (' water_back.pdf') Pagesize= (21 * cm, 29.7 * cm) cans.translate (10 * cm, 12 * cm) # move origin coordinates cans.setFont ('songti', 23) # set font to Song typeface, size 23 cans.setFillColorRGB (0.5,0.5,0.5) Set font background color cans.rotate (45) # set font tilt 45 degrees cans.drawString (- 7 * cm, 0 * cm, content) cans.drawString (7 * cm, 0 * cm, content) cans.drawString (0 * cm, 7 * cm, content) cans.drawString (0 * cm,-7 * cm Content) cans.save () # PDF file def insert_water_to_pdf (input_pdf, output_pdf) where the watermark is saved Water_pdf):''merge watermark into PDF file: param input_pdf: input file path: param output_pdf: output file path: param water_pdf: watermark file path: return:' 'water = PdfFileReader (water_pdf) # read watermark PDF water_page = water.getPage (0) # get the first page of watermark PDF pdf = PdfFileReader (input_pdf Strict=False) # read the file that needs to be watermarked pdf_writer = PdfFileWriter () # create the PDF file write object for page in range (pdf.getNumPages ()): # iterate through each page PDF object pdf_page = pdf.getPage (page) # get PDF's current page object pdf_page.mergePage (water_page) # merge the watermark page into the current page Pdf_writer.addPage (pdf_page) # adds the merged PDF object page to the PDF write object output_file = open (output_pdf 'wb') # Open the PDF output file pdf_writer.write (output_file) # write the file to the output file output_file.close () # close the write stream def main (diretory, current): if os.path.isdir (diretory): logger.info (' folder ['+ diretory +'] check successful!) Os.chdir (diretory) logger.info ('current path is [' + os.getcwd () +']') generate_water_pdf (current) logger.info ('watermark PDF file generated successfully!') For file_path, dir_names File_names in os.walk (ringing'+ os.getcwd ()): for file_name in file_names: try: name = file_name.split ('.') [0] if name = = 'water_back': continue else: File_name_path = os.path.join (file_path File_name) output_file_path = file_name_path.split ('.') [0] +'_ added watermark .pdf 'insert_water_to_pdf (file_name_path, output_file_path,' water_back.pdf') logger.info ('['+ file_name_path +'] complete watermark merge!') Except Exception as e: logger.error ('['+ file_name_path +'] exception occurs, execute next!) Logger.error ('exception message:' + repr (e)) else: logger.info ('folder [' + diretory +'] failed to verify!) If _ _ name__ = ='_ _ main__': main,'I am a watermark') so far, this article "how to add Chinese watermarks to PDF files in batches with Python" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report