pdfkit中from_string与HTML换行失效问题求助
解决pdfkit中换行不生效的问题
我来帮你搞定pdfkit里的换行问题!你遇到的情况其实是因为pdfkit对纯文本换行和HTML换行的处理逻辑不一样,咱们一个个来解决:
1. from_string 示例的修复
你用普通的\n换行符在from_string里不生效,是因为pdfkit默认会把传入的字符串当作HTML来解析,而HTML里的普通换行符会被忽略,只会显示成空格。要实现换行,你有两个选择:
- 使用HTML的换行标签
<br> - 用
<pre>标签包裹文本,保留原有的格式(包括换行和空格)
修改后的代码示例:
import pdfkit options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': 'UTF-8', 'quiet': '' } # 方法1:用<br>标签换行 s1 = 'a<br>b' # 方法2:用<pre>保留格式 # s1 = '<pre>a\n b</pre>' pdfkit.from_string(s1, 'out.pdf', options=options)
2. HTML 文件示例的修复
你的HTML示例里,把多行文本直接放在<p>标签中,HTML会自动把连续的空白字符(包括换行)合并成一个空格,所以看不到换行效果。解决方法同样是用HTML的换行标签,或者拆分段落:
方法1:使用 <br> 标签
修改你的s2内容,添加换行标签:
import pdfkit s2 = "a<br>b" h1 = """<html> <head></head> <body><p>""" h2 = """</p></body> </html>""" content = h1 + s2 + h2 with open('out.html', 'w') as f: f.write(content) options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': 'UTF-8', 'quiet': '' } pdfkit.from_file('out.html', 'out.pdf')
方法2:拆分多个 <p> 标签
如果希望每行是独立的段落,可以把s2拆分成多个<p>:
s2 = "<p>a</p><p>b</p>" h1 = """<html> <head></head> <body>""" h2 = """</body> </html>""" content = h1 + s2 + h2
方法3:使用 <pre> 标签保留原格式
如果想保留文本里的原始换行,可以用<pre>包裹内容:
s2 = """a b""" h1 = """<html> <head></head> <body><pre>""" h2 = """</pre></body> </html>""" content = h1 + s2 + h2
这样修改后,就能得到你想要的“a(换行)b”的效果了!
内容的提问来源于stack exchange,提问作者user11384282
相关产品推荐
相关产品推荐

