Advertisement
Guest User

Untitled

a guest
Jun 9th, 2023
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.28 KB | None | 0 0
  1. #DO ZROBIENIA - PRZYPADEK DLA PDF Z KILKOMA STRONAMI ZARÓWNO DLA FILL JAK I WATERMARK
  2.  
  3.  
  4. from datetime import datetime
  5. from pathlib import Path
  6.  
  7. import PyPDF2
  8. import docx
  9. from python_docx_replace import docx_replace
  10.  
  11. from reportlab.pdfgen import canvas
  12. from reportlab.lib.pagesizes import A4
  13. from reportlab.lib.units import mm, cm
  14. from reportlab.lib.styles import getSampleStyleSheet
  15. from reportlab.platypus import Paragraph, Frame
  16. import os
  17.  
  18.  
  19. today_date = datetime.now().strftime("%d.%m.%Y")
  20.  
  21. TEMPLATE_FILES_DIR = Path.cwd() / 'templates'
  22. OUTPUT_DIR = Path.cwd() / 'output'
  23.  
  24. INPUT_PROMPT = "Podaj w postaci cyfry do kogo chesz wygenerować wniosek np 1 lub wpisz lista jeżeli " \
  25. "nie wiesz jaka cyfra odpowiada wnioskowi lub exit jeżeli chcesz wyjśc z programu: "
  26. TEMPLATES = {
  27. "1": {
  28. "help_name": "Zarząd Drogowy w Pcimiu",
  29. "file_name": "PR do ZD w Pcimiu - Wniosek o uzgodnienie lokalizacji sieci i przyłącza gazowego",
  30. "docx_template_name": "ZDwOlkusz_template.docx",
  31. "replacements": {
  32. "today_date": today_date,
  33. "connection_plural_or_singular_uppercase": "PRZYŁĄCZY I", #PRZYŁĄCZY I, PRZYŁĄCZA I, "BLANK"
  34. "title": "xxxxx",
  35. "road_plots": "567/8",
  36. "city": "krakow",
  37. "street": "ul. Gałgana",
  38. "connection_plural_or_singular_lowercase": "przyłącza i"
  39. }
  40. },
  41. "2": {
  42. "help_name": "Przedsiębiorstwo Wodociagów i Kanalizacji Sp. z o.o. w Pcimiu",
  43. "file_name": "PR do PWiK w Pcimiu - Wniosek o uzgodnienie branżowe",
  44. "docx_template_name": "PWiKOlkusz_template.docx",
  45. "replacements": {
  46. "today_date": today_date,
  47. "title": "xxxxxxxx",
  48. }
  49. },
  50. "3": {
  51. "help_name": "TAURON Dystrybucja S.A Katowice",
  52. "file_name": "PR do Tauron - Wniosek o uzgodnienie branżowe",
  53. "pdf_template_name": "TauronKatowice_template.pdf",
  54. "pdf_needed_pages_number": "0", #ilość stron z których składa się wniosek (do wydruku) #narazie nie używane
  55. "replacements": {
  56. "TextField27[2]": "xxxxx",
  57. "TextField28[4]": " ", #dzialki
  58. "TextField27[3]": "xxxx", #gmina
  59. "TextField28[6]": "xx",
  60. "TextField27[4]": "xx", #miejscowość
  61. "TextField28[5]": "xxxxx",
  62. "plots": "567/8",
  63. "today_date": today_date
  64. }
  65. }
  66. }
  67.  
  68.  
  69. def create_docx_from_template(template: Path, output_dir: Path, replacements: dict[str, str]) -> Path:
  70. date = datetime.now().strftime("%Y-%m-%d")
  71.  
  72. doc = docx.Document(template)
  73. docx_replace(doc, **replacements)
  74.  
  75. output_path = output_dir / f"{date} {TEMPLATES[choice]['file_name']}.docx" #template.name ucina nazwę pliku ze blabla/costam.pdf = costam.pdf ścieżki (podaje ostatni człon z rozszerzeniem)
  76. doc.save(output_path)
  77.  
  78. return output_path
  79.  
  80.  
  81. def _print_help() -> None:
  82. for idx, data in TEMPLATES.items():
  83. print(f"{idx} - {data['help_name']}")
  84.  
  85.  
  86. def _generate_docx(choice: str) -> None:
  87. template_path = TEMPLATE_FILES_DIR / TEMPLATES[choice]["docx_template_name"]
  88. replacements = TEMPLATES[choice]["replacements"]
  89. output_path = create_docx_from_template(template_path, OUTPUT_DIR, replacements)
  90. print(f"Wniosek został wygenerowany: {output_path}")
  91.  
  92.  
  93.  
  94. def fill_and_generate_pdf(choice: str) -> Path:
  95.  
  96. #część do wypełniania gotowych pół w pdf plik help1
  97.  
  98. date = datetime.now().strftime("%Y-%m-%d")
  99. template_path = TEMPLATE_FILES_DIR / TEMPLATES[choice]["pdf_template_name"]
  100. reader = PyPDF2.PdfReader(template_path)
  101. writer = PyPDF2.PdfWriter()
  102. page = reader.pages[0]
  103. #fields = reader.get_form_text_fields()
  104. writer.add_page(page)
  105. writer.update_page_form_field_values(writer.pages[0], TEMPLATES[choice]["replacements"])
  106. output_path = OUTPUT_DIR / f"{date}_help1_{TEMPLATES[choice]['file_name']}.pdf"
  107.  
  108. with open(output_path, "wb") as filled_out_pdf:
  109. writer.write(filled_out_pdf)
  110. print("sciezka pierwszego wygenerowanego pliku", output_path)
  111.  
  112. return output_path
  113. #efekt końcowy to plik pdf o nazwie w środku help1
  114.  
  115.  
  116.  
  117. #część do rysowania nowych pół pdf plik help2
  118. def tauron(choice: str) -> Path:
  119. date = datetime.now().strftime("%Y-%m-%d")
  120. UNIT = mm
  121. #output_temporary_path = OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf"
  122. #print(output_temporary_path) #C:\Users\Administrator\Pulpit\Programowanie\Python\kod\example\output\2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branżowe.pdf
  123. #c = canvas.Canvas("output_temporary_path", pagesize=A4)
  124. c = canvas.Canvas("output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf", pagesize=A4)
  125. #c = canvas.Canvas(OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf", pagesize=A4)
  126. output_path = OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf"
  127.  
  128. width, height = A4
  129. styleSheet = getSampleStyleSheet()
  130. style = styleSheet['BodyText']
  131.  
  132.  
  133. def making_fields(x_field_coord: int, y_field_coord: int, field_width: int, field_height: int) -> int:
  134. result_list = [n*UNIT for n in (x_field_coord, y_field_coord, field_width, field_height)]
  135. return result_list
  136.  
  137. text = "dupa" #TEMPLATES[choice]['replacements'][plots]
  138. plots = []
  139. plots.append(Paragraph(text, style))
  140.  
  141. text2 = "dupa2" #f"Przeginia, {TEMPLATES[choice]['replacements'][today_date]}"
  142. city_and_today_date = []
  143. city_and_today_date.append(Paragraph(text2, style))
  144.  
  145. f_plots = Frame(*making_fields(158, 156, 43, 15), leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, id=None, showBoundary=0)
  146. f_city_date = Frame(*making_fields(8, 31, 95, 11), leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, id=None, showBoundary=0)
  147. f_plots.addFromList(plots, c)
  148. f_city_date.addFromList(city_and_today_date, c)
  149. c.showPage()
  150. c.save()
  151. print("sciezka drugiego wygenerowanego pliku", output_path)
  152.  
  153. return output_path
  154.  
  155. #tu sie kończy tworzenie pliku help2
  156.  
  157. def merge_fields_with_template(template_file, fields_template):
  158. date = datetime.now().strftime("%Y-%m-%d")
  159. output_path = OUTPUT_DIR / f"{date} {TEMPLATES[choice]['file_name']}.pdf"
  160. # Open the template PDF and fields files in read-binary mode
  161. with open(template_file, 'rb') as file:
  162. pdf = PyPDF2.PdfReader(file)
  163.  
  164. # Open the fields PDF in read-binary mode
  165. with open(fields_template, 'rb') as fields:
  166. fields_pdf = PyPDF2.PdfReader(fields)
  167.  
  168. # Get the first page of the template PDF
  169. page = pdf.pages[0]
  170.  
  171. # Merge the fields PDF with the template PDF page as an overlay
  172. page.merge_page(fields_pdf.pages[0])
  173.  
  174. # Create a new PDF writer object
  175. writer = PyPDF2.PdfWriter()
  176.  
  177. # Add the modified page to the writer
  178. writer.add_page(page)
  179.  
  180. # Write the modified PDF to the output file
  181. with open(output_path, 'wb') as output:
  182. writer.write(output)
  183.  
  184. # Provide the template PDF file, fields PDF file, and the output file name
  185.  
  186. print(f"Wniosek został wygenerowany: {output_path}")
  187.  
  188. return output_path
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195. if __name__ == "__main__":
  196. while (choice := input(INPUT_PROMPT)) != "exit":
  197.  
  198. if choice == "lista":
  199. _print_help()
  200. elif choice == "3":
  201. merge_fields_with_template(fill_and_generate_pdf(choice), tauron(choice))
  202. #merge_fields_with_template(fill_and_generate_pdf(choice), "output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf")
  203. #merge_fields_with_template("output/2023-06-09_help1_PR do Tauron - Wniosek o uzgodnienie branżowe.pdf", "output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf") # output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf
  204. elif choice in TEMPLATES.keys():
  205. _generate_docx(choice)
  206. else:
  207. print(f"Nieznana komenda!")
  208.  
  209.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement