How to draw a line every 25 words?

[亡魂溺海] 提交于 2019-11-30 10:00:28

问题


Using iTextSharp, I create a pdf writing some text into it. What I need is to draw a line to delimiter the text every 25 words, like the following image:

Basically, I need to do that: draw a line every 25 words, just like the image.

I'm aware there's a way of finding the position of a word on a page, but considering I'm writing the text to the pdf file, I guess there could be a way of calculating this without really having to find the text position, right?


回答1:


Please take a look at the Every25Words examples. In that example, I read a text file into a String with the readFile() method. I then split the text into words based on the occurrence of spaces, and I add each word one by one:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    writer.setPageEvent(new WordCounter());
    writer.setInitialLeading(16);
    document.open();
    String[] words = readFile().split("\\s+");
    Chunk chunk = null;
    for (String word : words) {
        if (chunk != null) {
            document.add(new Chunk(" "));
        }
        chunk = new Chunk(word);
        chunk.setGenericTag("");
        document.add(chunk);
    }
    document.close();
}

The magic happens in this line:

writer.setPageEvent(new WordCounter());

chunk.setGenericTag("");

First we declare an instance of the WordCounter event. You may choose a better name for that class, as not only does it count words, it also draws a dashed line:

public class WordCounter extends PdfPageEventHelper {

    public int count = 0;

    @Override
    public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
        count++;
        if (count % 25 == 0) {
            PdfContentByte canvas = writer.getDirectContent();
            canvas.saveState();
            canvas.setLineDash(5, 5);
            canvas.moveTo(document.left(), rect.getBottom());
            canvas.lineTo(rect.getRight(), rect.getBottom());
            canvas.lineTo(rect.getRight(), rect.getTop());
            canvas.lineTo(document.right(), rect.getTop());
            canvas.stroke();
            canvas.restoreState();
        }
    }
}

Do you see what we do between the saveState() and restoreState() method? We define a dash pattern, we move to the left of the page, we construct a path to the right of the word, then we draw a short upwards line, to finish the path with a line to the right. Once the path is constructed, we stroke the line.

This onGenericTag() method will be triggered every time a Chunk is added on which we used the setGenericTag method.

This is what the result looks like every25words.pdf:



来源:https://stackoverflow.com/questions/28709603/how-to-draw-a-line-every-25-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!