Advertisement
nicuf

fpdf library - convert html to PDF

Jul 26th, 2023
887
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.99 KB | None | 0 0
  1. from fpdf import fpdf, html
  2. from fpdf import FPDF
  3. import os
  4. import re
  5.  
  6. from PyPDF2 import PdfFileMerger
  7.  
  8. dict_simboluri = {
  9.     'ă': 'ă',
  10.     'â': 'â',
  11.     'ã': 'ã',
  12.     'â': 'â',
  13.     'ă': 'ă',
  14.     'â': 'a',
  15.     ' ': ' ',
  16.     'î': 'î',
  17.     'Î': 'Î',
  18.     'î': 'î',
  19.     'î': 'î',
  20.     'Î': 'Î',
  21.     'Ș': 'Ș',
  22.     'ș': 'ș',
  23.     'Ş': 'Ş',
  24.     'ș': 'ș',
  25.     'ş': 'ș',
  26.     ' ': ' ',
  27.     'ț': 'ț',
  28.     'ţ': 'ț',
  29.     'Ţ': 'Ţ',
  30.     'ț': 'ț',
  31.     '&': ''
  32. }
  33.  
  34. class PDF(FPDF):
  35.     def set_pdf_title(self, file_path):
  36.         title = ''  # Inițializează titlul cu un șir vid
  37.  
  38.         with open(file_path, 'r', encoding='utf-8') as file:
  39.             file_content = file.read()
  40.  
  41.         title_match = re.search('<title>(.*?) \|', file_content)
  42.         if title_match:
  43.             title = title_match.group(1).strip()
  44.  
  45.         if title:  # Verifică dacă s-a găsit un titlu
  46.             self.set_font('Kanit', 'B', 12)
  47.             self.cell(0, 10, f'Articole {title}', 0, 1, 'C')
  48.         else:
  49.             self.set_font('Kanit', 'B', 12)
  50.             self.cell(0, 10, 'Articole', 0, 1, 'C')
  51.  
  52.     def header(self):
  53.         self.set_pdf_title(self.file_path)
  54.  
  55.     def chapter_title(self, title):
  56.         self.set_font('Kanit', 'B', 14)  # dimensiune 14, stil bold
  57.         self.set_text_color(204, 0, 0)  # rosu pentru titlu
  58.         self.cell(0, 10, title, 0, 1, 'L')
  59.         self.set_text_color(0, 0, 0)  # resetează culoarea la negru
  60.  
  61.     def chapter_date(self, date):
  62.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  63.         self.cell(0, 10, date, 0, 1, 'L')
  64.  
  65.     def chapter_body(self, lead):
  66.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  67.         self.cell(0, 10, lead, 0, 1, 'L')
  68.  
  69.     def add_link(self, link):
  70.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  71.         self.set_text_color(0, 0, 255)  # albastru pentru link
  72.         self.cell(0, 10, 'Link: ' + link, 0, 1, 'L', link=link)
  73.         self.set_text_color(0, 0, 0)  # resetează culoarea la negru
  74.  
  75. def save_to_pdf(directory_path):
  76.     for root, dirs, files in os.walk(directory_path):
  77.         for file_name in files:
  78.             if file_name.endswith(".html"):
  79.                 file_path = os.path.join(root, file_name)
  80.                 with open(file_path, 'r', encoding='utf-8') as file:
  81.                     file_content = file.read()
  82.  
  83.                 if '<!-- ARTICOL CATEGORIE START -->' in file_content:
  84.                     # creare fisier PDF
  85.                     pdf = PDF()
  86.                     pdf.set_auto_page_break(auto=True, margin=15)
  87.                     pdf.add_font("Kanit", fname="fonts/Kanit-Regular.ttf")
  88.                     pdf.add_font("Kanit", style="B", fname="fonts/Kanit-Bold.ttf")
  89.                     pdf.add_font("Kanit", style="I", fname="fonts/Kanit-Italic.ttf")
  90.                     pdf.add_font("Kanit", style="BI", fname="fonts/Kanit-BoldItalic.ttf")
  91.                     pdf.set_font("Kanit", size=12)
  92.                     pdf.file_path = file_path  # Setează calea fișierului curent
  93.  
  94.                     titluri_articole = re.findall('class="linkMare">(.*?)</a></span>', file_content)
  95.                     date_articole = re.findall('<td class="text_dreapta">(.*?), in <a href="', file_content)
  96.                     leads_articole = re.findall('<p class="text_obisnuit2"><em>(.*?)</em></p>', file_content)
  97.                     linkuri_articole = re.findall('id="external2"><a href="(.*)">cite&#351;te', file_content)
  98.  
  99.                     if len(titluri_articole) == len(date_articole) == len(leads_articole) == len(linkuri_articole):
  100.                         pdf.add_page()
  101.  
  102.                         for i in range(len(titluri_articole)):
  103.                             titlu_articol = titluri_articole[i]
  104.                             for simbol in dict_simboluri.keys():
  105.                                 titlu_articol = titlu_articol.replace(simbol, dict_simboluri[simbol])
  106.  
  107.                             data_articol = date_articole[i]
  108.  
  109.                             lead_articol = leads_articole[i]
  110.                             for simbol in dict_simboluri.keys():
  111.                                 lead_articol = lead_articol.replace(simbol, dict_simboluri[simbol])
  112.  
  113.                             link_articol = ''
  114.                             if i < len(linkuri_articole):  # Verifică dacă există un link disponibil
  115.                                 link_articol = linkuri_articole[i]
  116.  
  117.                             pdf.chapter_title(titlu_articol)
  118.                             pdf.chapter_date(data_articol)
  119.                             pdf.chapter_body(lead_articol)
  120.                             pdf.add_link(link_articol)
  121.                             pdf.cell(0, 10, '-------------------', 0, 1, 'L')
  122.  
  123.                         den_fisier = file_path.split('.')[0] + '.pdf'
  124.                         pdf.output(den_fisier)
  125.  
  126.                     else:
  127.                         print("Numarul de titluri, date, leads sau linkuri nu se potrivesc în fișierul --- {} ---.".format(file_path))
  128.                         print("Titluri: ", len(titluri_articole))
  129.                         print("Date: ", len(date_articole))
  130.                         print("Leads: ", len(leads_articole))
  131.                         print("Linkuri: ", len(linkuri_articole))
  132.  
  133. def merge_pdf_files(directory_path):
  134.     merger = PdfFileMerger()
  135.     for root, dirs, files in os.walk(directory_path):
  136.         for file_name in files:
  137.             if file_name.endswith(".pdf"):
  138.                 print("PDF: ", file_name)
  139.                 file_path = os.path.join(root, file_name)
  140.                 merger.append(file_path)
  141.         merger.write(os.path.join(root, "articles.pdf"))
  142.         merger.close()
  143.         break
  144.  
  145. directory_path = "c:\\Folder5\\"  # înlocuiește cu calea către directorul cu fișierele HTML
  146. save_to_pdf(directory_path)
  147. merge_pdf_files(directory_path)
  148.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement