How to add paragraph and then a line?

眉间皱痕 提交于 2019-12-07 11:19:41

问题


All of the examples I have seen so far using ITextSharp start from scratch and create a new document, add something to it and close it. What if I need to do multiple things to a PDF for example I want to add a paragraph and then add a line. For example if I run this simple console app in which I just create a PDF and add a paragraph and then close it everything runs fine.

class Program
{
    static void Main(string[] args)
    {
        Document pdfDoc = new Document();
        PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.Create));
        pdfDoc.Open();

        pdfDoc.Add(new Paragraph("Some Text added"));

        pdfDoc.Close();

        Console.WriteLine("The file was created.");
        Console.ReadLine();
    }
}

However if I need to do something else like draw a line like this

class Program
{
    static void Main(string[] args)
    {
        Document pdfDoc = new Document();
        PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.Create));
        pdfDoc.Open();

        pdfDoc.Add(new Paragraph("Some Text added"));

        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate));
        PdfContentByte cb = writer.DirectContent;
        cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2);
        cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
        cb.Stroke();
        writer.Close();

        pdfDoc.Close();

        Console.WriteLine("The file was created.");
        Console.ReadLine();
    }
}

I get an error when trying to open the file because it is already opened by pdfDoc. If I put the highlighted code after the pdfDoc.Close() I get an error saying "The Document is not opened" How do I switch from adding text to adding a line? Do I need to close the doc and then re-open it again with the PDFReader and modify it there or can I do it all at once?


回答1:


You're getting an error because you're trying to request a second instance of a PDFWriter when you already have one. The second PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate)); is not needed. I made a small edit to your code and this now seems to work

Document pdfDoc = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate));

pdfDoc.Open();
pdfDoc.Add(new Paragraph("Some Text added"));             
PdfContentByte cb = writer.DirectContent;
cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2);
cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
cb.Stroke();

pdfDoc.Close();

Console.WriteLine("The file was created.");
Console.ReadLine();


来源:https://stackoverflow.com/questions/3366490/how-to-add-paragraph-and-then-a-line

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