我使用的是itext7的社区版本(7.1.9
版本)。我想创建一个PDF文档,在其中插入文本段落,并在其中插入一个横向分隔符:
some interesting text
-----------
more interesting text
-----------
still interesting text
-----------
you get the idea
-----------
为了实现这个文档结构,我使用Paragraph
和LineSeparator
与DashedLine
类结合使用。然而,即使用一个最小的例子,单独的破折号最终也会变成垂直,如下所示:
some interesting text
|||||||||||||
more interesting text
|||||||||||||
整体分隔符仍然水平运行,但是传递一个width
参数(如Javadoc中定义的)似乎实际上给了行高度。我在这里做错什么了吗?
如何生成带有水平虚线的分隔符,其中虚线本身也是水平的(宽度为30.0是一个通用示例)?
最小复制示例(Kotlin):
import com.itextpdf.io.font.constants.StandardFonts
import com.itextpdf.kernel.font.PdfFontFactory
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.kernel.pdf.canvas.draw.DashedLine
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.LineSeparator
import com.itextpdf.layout.element.Paragraph
import java.io.File
object DashedLineBugReproduction {
private fun render() {
val docWriter = PdfWriter(File("/tmp/foobar_dashes.pdf"))
val document = PdfDocument(docWriter)
document.writeContents()
document.close()
}
fun PdfDocument.writeContents() {
val doc = Document(this)
val font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN)
val dashedLine = LineSeparator(DashedLine(30f))
val paragraph = Paragraph("Lorem ipsum dolor sit amet.")
.setFont(font)
.setFontSize(20f)
doc.add(dashedLine)
for (i in 0 until 8) {
doc.add(paragraph)
doc.add(dashedLine)
}
doc.close()
}
@JvmStatic
fun main(args: Array<String>) {
render()
}
}
结果输出文件(屏幕截图,如果需要,我可以提供PDF ):
发布于 2019-12-25 17:47:08
宽度参数不设置线段的宽度,而是设置水平线的宽度,这恰好是由段组成的,因此这里没有错误。
默认情况下,段之间的距离在DashedLine
中是不可配置的,但是您可以创建自己的类并重写draw
操作来创建自己的外观。
如果您希望您的行包含较长的段,则可以使用unitsOn
、unitsOff
和setLineDash
方法的phase
参数。这里只是一个参考实现和可视化结果:
private static class CustomDashedLine extends DashedLine {
public CustomDashedLine(float lineWidth) {
super(lineWidth);
}
@Override
public void draw(PdfCanvas canvas, Rectangle drawArea) {
canvas.saveState()
.setLineWidth(getLineWidth())
.setStrokeColor(getColor())
.setLineDash(20, 4, 2)
.moveTo(drawArea.getX(), drawArea.getY() + getLineWidth() / 2)
.lineTo(drawArea.getX() + drawArea.getWidth(), drawArea.getY() + getLineWidth() / 2)
.stroke()
.restoreState();
}
}
创建LineSeparator
时只需使用此新实现即可
LineSeparator dashedLine = new LineSeparator(new CustomDashedLine(3f));
结果如下:
https://stackoverflow.com/questions/59444114
复制相似问题