Advertisement
nicuf

html tags convert to pdf

Jan 11th, 2024
920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.05 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.     '&': ''
  35. }
  36.  
  37. class PDF(FPDF):
  38.     def set_pdf_title(self, file_path):
  39.         title = ''  # Inițializează titlul cu un șir vid
  40.  
  41.         with open(file_path, 'r', encoding='utf-8') as file:
  42.             file_content = file.read()
  43.  
  44.         title_match = re.search('<title>(.*?) \|', file_content)
  45.         if title_match:
  46.             title = title_match.group(1).strip()
  47.  
  48.         if title:  # Verifică dacă s-a găsit un titlu
  49.             self.set_font('Kanit', 'B', 12)
  50.             self.cell(0, 10, f'Articole {title}', 0, 1, 'C')
  51.         else:
  52.             self.set_font('Kanit', 'B', 12)
  53.             self.cell(0, 10, 'Articole', 0, 1, 'C')
  54.  
  55.     def header(self):
  56.         self.set_pdf_title(self.file_path)
  57.  
  58.     def chapter_title(self, title):
  59.         self.set_font('Kanit', 'B', 14)  # dimensiune 14, stil bold
  60.         self.set_text_color(204, 0, 0)  # rosu pentru titlu
  61.         self.cell(0, 10, title, 0, 1, 'L')
  62.         self.set_text_color(0, 0, 0)  # resetează culoarea la negru
  63.  
  64.     def chapter_date(self, date):
  65.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  66.         self.cell(0, 10, date, 0, 1, 'L')
  67.  
  68.     def chapter_body(self, lead):
  69.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  70.         self.cell(0, 10, lead, 0, 1, 'L')
  71.  
  72.     def add_link(self, link):
  73.         self.set_font('Kanit', '', 12)  # dimensiune 12, stil normal
  74.         self.set_text_color(0, 0, 255)  # albastru pentru link
  75.         self.cell(0, 10, 'Link: ' + link, 0, 1, 'L', link=link)
  76.         self.set_text_color(0, 0, 0)  # resetează culoarea la negru
  77.  
  78. # ...
  79.  
  80. def save_to_pdf(directory_path):
  81.     for root, dirs, files in os.walk(directory_path):
  82.         for file_name in files:
  83.             file_path = os.path.join(root, file_name)
  84.             if file_name.endswith(".html"):
  85.                 try:
  86.                     with open(file_path, 'r', encoding='utf-8') as file:
  87.                         file_content = file.read()
  88.                 except UnicodeDecodeError:
  89.                     with open(file_path, 'r', encoding='latin-1') as file:
  90.                         file_content = file.read()
  91.  
  92.                 if '<!-- ARTICOL CATEGORIE START -->' in file_content:
  93.                     # creare fisier PDF
  94.                     pdf = PDF()
  95.                     pdf.set_auto_page_break(auto=True, margin=15)
  96.                     pdf.add_font("Kanit", fname="e:/Carte/BB/17 - Site Leadership/alte/Ionel Balauta/Aryeht/Task 1 - Traduce tot site-ul/Doar Google Web/Andreea/Meditatii/Sedinta 20 august 2022/fonts/Kanit-Regular.ttf")
  97.                     pdf.add_font("Kanit", style="B", fname="e:/Carte/BB/17 - Site Leadership/alte/Ionel Balauta/Aryeht/Task 1 - Traduce tot site-ul/Doar Google Web/Andreea/Meditatii/Sedinta 20 august 2022/fonts/Kanit-Bold.ttf")
  98.                     pdf.add_font("Kanit", style="I", fname="e:/Carte/BB/17 - Site Leadership/alte/Ionel Balauta/Aryeht/Task 1 - Traduce tot site-ul/Doar Google Web/Andreea/Meditatii/Sedinta 20 august 2022/fonts/Kanit-Italic.ttf")
  99.                     pdf.add_font("Kanit", style="BI", fname="e:/Carte/BB/17 - Site Leadership/alte/Ionel Balauta/Aryeht/Task 1 - Traduce tot site-ul/Doar Google Web/Andreea/Meditatii/Sedinta 20 august 2022/fonts/Kanit-BoldItalic.ttf")
  100.  
  101.                     pdf.set_font("Kanit", size=12)
  102.                     pdf.file_path = file_path  # Setează calea fișierului curent
  103.  
  104.                     # Preluare titluri
  105.                     titluri_articole = re.findall('class="linkMare">(.*?)</a></span>', file_content)
  106.                     if not titluri_articole:
  107.                         print(f"Nu s-au găsit titluri în fișierul {file_path}.")
  108.                         continue
  109.  
  110.                     # Preluare date
  111.                     date_articole = re.findall('<td class="text_dreapta">(.*?), in <a href="', file_content)
  112.                     if not date_articole:
  113.                         print(f"Nu s-au găsit date în fișierul {file_path}.")
  114.                         continue
  115.  
  116.                     # Preluare leads
  117.                     leads_articole = re.findall('<p class="text_obisnuit2"><em>(.*?)</em></p>', file_content)
  118.                     if not leads_articole:
  119.                         print(f"Nu s-au găsit lead-uri în fișierul {file_path}.")
  120.                         continue
  121.  
  122.                     # Preluare linkuri
  123.                     linkuri_articole = re.findall('id="external2"><a href="(.*)">read more', file_content)
  124.                     if not linkuri_articole:
  125.                         print(f"Nu s-au găsit linkuri în fișierul {file_path}.")
  126.                         continue
  127.  
  128.                     if len(titluri_articole) == len(date_articole) == len(leads_articole) == len(linkuri_articole):
  129.                         pdf.add_page()
  130.  
  131.                         for i in range(len(titluri_articole)):
  132.                             titlu_articol = titluri_articole[i]
  133.                             # ...
  134.                             data_articol = date_articole[i]
  135.                             # ...
  136.                             lead_articol = leads_articole[i]
  137.                             # ...
  138.                             link_articol = ''
  139.                             if i < len(linkuri_articole):  # Verifică dacă există un link disponibil
  140.                                 link_articol = linkuri_articole[i]
  141.  
  142.                             pdf.chapter_title(titlu_articol)
  143.                             pdf.chapter_date(data_articol)
  144.                             pdf.chapter_body(lead_articol)
  145.                             pdf.add_link(link_articol)
  146.                             pdf.cell(0, 10, '-------------------', 0, 1, 'L')
  147.  
  148.                         den_fisier = file_path.split('.')[0] + '.pdf'
  149.                         pdf.output(den_fisier)
  150.  
  151.                     else:
  152.                         print("Numarul de titluri, date, leads sau linkuri nu se potrivesc în fișierul --- {} ---.".format(file_path))
  153.                         print("Titluri: ", len(titluri_articole))
  154.                         print("Date: ", len(date_articole))
  155.                         print("Leads: ", len(leads_articole))
  156.                         print("Linkuri: ", len(linkuri_articole))
  157.                 else:
  158.                     print(f"Fișierul {file_path} nu conține markerul <!-- ARTICOL CATEGORIE START --> și va fi ignorat.")
  159.  
  160.  
  161.  
  162. from pdfrw import PdfReader, PdfWriter, errors
  163.  
  164. def merge_pdf_files(directory_path):
  165.     writer = PdfWriter()
  166.     for root, dirs, files in os.walk(directory_path):
  167.         for file_name in files:
  168.             if file_name.endswith(".pdf"):
  169.                 file_path = os.path.join(root, file_name)
  170.                 try:
  171.                     reader = PdfReader(file_path)
  172.                     if not reader.pages:  # Verifică dacă fișierul PDF are pagini
  173.                         print(f"Fișierul {file_name} este gol și va fi ignorat.")
  174.                         continue
  175.                     for page in reader.pages:
  176.                         writer.addPage(page)
  177.                 except errors.PdfParseError:  # Tratează cazul în care fișierul PDF este corupt
  178.                     print(f"Fișierul {file_name} este corupt și va fi ignorat.")
  179.                     continue
  180.         writer.write(os.path.join(root, "articles-categorii.pdf"))
  181.         break
  182.  
  183.  
  184. directory_path = "c:\\Folder9\\"  # înlocuiește cu calea către directorul cu fișierele HTML
  185. save_to_pdf(directory_path)
  186. merge_pdf_files(directory_path)
  187.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement