Coverage for gws-app/gws/lib/htmlx/__init__.py: 0%

29 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 01:37 +0200

1import gws 

2import gws.lib.osx 

3import gws.lib.uom 

4 

5 

6def render_to_pdf(html, out_path: str, page_size: gws.UomSize = None, page_margin: gws.UomExtent = None) -> str: 

7 

8 mar = page_margin or (0, 0, 0, 0, gws.Uom.mm) 

9 

10 # page sizes need to be in mm! 

11 psz = (210, 297, gws.Uom.mm) 

12 if page_size: 

13 psz = gws.lib.uom.size_to_mm(page_size, gws.lib.uom.PDF_DPI) 

14 

15 gws.u.write_file(out_path + '.html', html) 

16 

17 def f(x): 

18 return str(int(x)) 

19 

20 cmd = [ 

21 'wkhtmltopdf', 

22 '--disable-javascript', 

23 '--disable-smart-shrinking', 

24 '--load-error-handling', 'ignore', 

25 '--enable-local-file-access', 

26 '--dpi', f(gws.lib.uom.PDF_DPI), 

27 '--margin-top', f(mar[0]), 

28 '--margin-right', f(mar[1]), 

29 '--margin-bottom', f(mar[2]), 

30 '--margin-left', f(mar[3]), 

31 '--page-width', f(psz[0]), 

32 '--page-height', f(psz[1]), 

33 'page', 

34 out_path + '.html', 

35 out_path, 

36 ] 

37 

38 gws.lib.osx.run(cmd) 

39 return out_path 

40 

41 

42def render_to_png(html, out_path: str, page_size: gws.UomSize = None, page_margin: list[int] = None) -> str: 

43 if page_margin: 

44 mar = page_margin 

45 html = f""" 

46 <body style="margin:{mar[0]}px {mar[1]}px {mar[2]}px {mar[3]}px"> 

47 {html} 

48 </body> 

49 """ 

50 

51 gws.u.write_file(out_path + '.html', html) 

52 

53 cmd = ['wkhtmltoimage'] 

54 

55 def f(x): 

56 return str(int(x)) 

57 

58 if page_size: 

59 # page sizes need to be in px! 

60 psz = gws.lib.uom.size_to_px(page_size, gws.lib.uom.PDF_DPI) 

61 w, h, _ = psz 

62 cmd.extend([ 

63 '--width', f(w), 

64 '--height', f(h), 

65 '--crop-w', f(w), 

66 '--crop-h', f(h), 

67 ]) 

68 

69 cmd.extend([ 

70 '--disable-javascript', 

71 '--disable-smart-width', 

72 '--transparent', 

73 '--enable-local-file-access', 

74 out_path + '.html', 

75 out_path, 

76 ]) 

77 

78 gws.lib.osx.run(cmd) 

79 return out_path