xml ,xsl-fo 导出pdf

521 阅读1分钟

场景是需要前端调好样式

1. html 转xsl

www.re.be/index.xhtml, html 转 xsl

www.re.be/css2xslfo/i…

sourceforge.net/projects/cs… css to xslfo

chmod +x css2xslfo1_6_2.jar
tidy -asxhtml -indent -wrap -1 /Users/cindychen/Downloads/xml-tranfer/table.html > \
    /Users/cindychen/Downloads/xml-tranfer/transfer.html
java -jar css2xslfo1_6_2.jar transfer.html -fo dist.xml    
​

XSL-FO 教程:www.w3chtml.com/xsl-fo/bloc…

2. 解决比例问题

// A4 纸 210mm * 297mm
<fo:simple-page-master master-name="blank" writing-mode="lr-tb" page-height="297mm" page-width="210mm" margin-top="0" margin-bottom="0" margin-left="0" margin-right="0">
// 调整 root 字体 大小
<fo:root font-selection-strategy="character-by-character" line-height-shift-adjustment="disregard-shifts" country="GB" font-family="serif" font-size="6pt" language="en">
// 单位用em
<fo:block margin-left="0pt" margin-right="0pt" unicode-bidi="embed" font-size="1.0em" line-height="1.625em">

pt (point,磅): 是一个物理长度单位,指的是72分之一英寸。

px (pixel,像素): 是一个虚拟长度单位,是计算机系统的数字化图像长度单位,如果px要换算成物理长度,需要指定精度DPI(Dots Per Inch,每英寸像素数),在扫描打印时一般都有DPI可选。Windows系统默认是96dpi,Apple系统默认是72dpi。

em(相对长度单位,相对于当前对象内文本的字体尺寸): 是一个相对长度单位,最初是指字母M的宽度,故名em。现指的是字符宽度的倍数,用法类似百分比,如:0.8em, 1.2em,2em等。通常1em=16px。

字号: 是中文字库中特有的一种单位,以中文代号表示特定的磅值pt,便于记忆、表述。

pt和px的换算公式可以根据pt的定义得出:

pt = 1/72(英寸), px = 1/dpi(英寸)

因此 pt = px * dpi / 72

以 Windows 下的 96dpi 来计算,1 pt = px * 96/72 = px * 4/3

3. CSS px 转 em 脚本

import re
​
def px_2_em(matched):
  value = matched.group(0)
  n= int(value[0:-2]) / 16
  return str(n) + 'em'# replace: {n}px / 16 -> {x}em
def replace(string):
  regexp = r'[0-9]+px'
  result = re.sub( regexp, px_2_em , string)
  return result
​
def start(originFile, saveFle):
  with open(originFile, 'r') as f:
    # get string
    string = f.read()
    # replace
    res = replace(string)
    # write
    newFile = open(saveFle, "w+")
    newFile.write(res)
    newFile.close()
    # close file
    f.close()
​
start('./table.html','./table_em.html')
​

\