31

iTextを使用してすべてのページに総ページ数を追加する方法は?

4

11 に答える 11

15
  1. PdfWritera から aへの出力をbytestreamダミーのページ数で最初に処理します。
  2. PdfReaderそのから を作成しbytestream、呼び出しPdfReader.getNumberOfPagesて実際のページ数を取得します。
  3. ページ数を把握し、それに応じてフッターを変更して、PDF 出力を再作成します。

面倒ですが、2 パスのアプローチなしにページ数を知る簡単な方法はありません。PDF の操作の詳細については、サンプル コードを参照してください。

于 2009-04-17T10:50:36.467 に答える
8

次のように、これらの 2 つの関数を継承してPdfPageEventHelper オーバーライドするクラスを作成できます。

Imports System.Collections.Generic
Imports System.Text

Imports iTextSharp.text.pdf
Imports iTextSharp.text

Namespace PDF_EnteteEtPiedDePage
    Public Class EnteteEtPiedDePage
        Inherits PdfPageEventHelper
        ' This is the contentbyte object of the writer
        Private cb As PdfContentByte

        ' we will put the final number of pages in a template
        Private template As PdfTemplate

        ' this is the BaseFont we are going to use for the header / footer
        Private bf As BaseFont = Nothing

        ' This keeps track of the creation time
        Private PrintTime As DateTime = DateTime.Now

        ' we override the onOpenDocument method
        Public Overrides Sub OnOpenDocument(writer As PdfWriter, document As Document)
            Try
                PrintTime = DateTime.Now
                bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
                cb = writer.DirectContent
                template = cb.CreateTemplate(50, 50)
            Catch de As DocumentException
            Catch ioe As System.IO.IOException
            End Try
        End Sub

        Public Overrides Sub OnStartPage(writer As PdfWriter, document As Document)
            MyBase.OnStartPage(writer, document)

            Dim pageSize As Rectangle = document.PageSize

        End Sub

        Public Overrides Sub OnEndPage(writer As PdfWriter, document As Document)
            MyBase.OnEndPage(writer, document)

            Dim pageN As Integer = writer.PageNumber
            Dim text As [String] = "Page " & pageN & " de "
            Dim len As Single = bf.GetWidthPoint(text, 8)

            Dim pageSize As Rectangle = document.PageSize

            cb.SetRGBColorFill(100, 100, 100)

            cb.BeginText()
            cb.SetFontAndSize(bf, 8)
            cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30))
            cb.ShowText(text)
            cb.EndText()

            cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30))

            cb.BeginText()
            cb.SetFontAndSize(bf, 8)
            cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Imprimé le : " & PrintTime.ToShortDateString() & " à " & PrintTime.ToShortTimeString, pageSize.GetRight(40), pageSize.GetBottom(30), 0)
            cb.EndText()
        End Sub

        Public Overrides Sub OnCloseDocument(writer As PdfWriter, document As Document)
            MyBase.OnCloseDocument(writer, document)

            template.BeginText()
            template.SetFontAndSize(bf, 8)
            template.SetTextMatrix(0, 0)
            template.ShowText("" & Convert.ToString((writer.PageNumber - 1)))
            template.EndText()
        End Sub

    End Class
End Namespace

その後、次のpdfwriter PageEvent ように値を設定します。

Dim PageEventHandler = New EnteteEtPiedDePage()
            aPdfWriter.PageEvent = PageEventHandler
于 2012-08-23T17:17:17.743 に答える
4

これ以上検索する必要はありません。ここに解決策があります。彼らがこのリンクを削除した場合、私は自分のサイトにコードを投稿し、リンクをホストします.

iText ページ番号の例

于 2012-01-05T18:13:47.007 に答える
3

これが私が使用したコードです。ページを出力に書き込むためのオーバーヘッドが増えることはありません。

outputStream = new ByteArrayOutputStream();
output = new DataOutputStream(outputStream);
document = new Document();
writer = PdfWriter.getInstance(document, output);
document.open();
contentByte = writer.getDirectContent();
....add stuff
document.close();
writer.close();
byte[] output = outputStream.toByteArray();
PdfReader reader = new PdfReader(output);
//reset the output
outputStream = new ByteArrayOutputStream();
output = new DataOutputStream(outputStream);
document = new Document();
writer = PdfWriter.getInstance(document, output);
document.open();
PdfStamper stamper = new PdfStamper(reader, outputStream);
//add the pages
for (int i = 1; i <= pageCount; i++)
{
    contentByte = stamper.getOverContent(i);
    addParagraph("Page " + i + " of " + pageCount, new Point(500, 30), boldTextFont);  // my own paragraph font
}
stamper.close();
于 2011-07-16T01:53:55.687 に答える
2

これを思い出させるために、簡単なWeb検索から。を見てみましょう

関連するメソッドはonEndPage()、「X」onCloseDocument()を生成し、ドキュメントの最後に到達したら「Y」を生成することです。

于 2009-04-17T10:43:35.173 に答える
1

ここに便利な機能があります!(Milhous のアプローチに基づく) (これは itext バージョン 4.1.6.0 を使用します)

public static byte[] AddPageNumbers(byte[] pdf)
        {
            PdfReader reader = new PdfReader(pdf);
            var Pages = reader.NumberOfPages;
            MemoryStream ms = new MemoryStream();

            PdfStamper stamper = new PdfStamper(reader, ms);
            for (int i = 1; i <= Pages; i++)
            {
                PdfContentByte overContent;
                Font Signature = FontFactory.GetFont("Calibiri", 9, iTextSharp.text.Font.NORMAL, Color.BLACK);
                overContent = stamper.GetOverContent(i);
                var helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                overContent.SaveState();
                overContent.BeginText();
                overContent.SetFontAndSize(helv, 10.0f);
                overContent.SetTextMatrix(PageSize.LETTER.Width / 2 - 20, PageSize.LETTER.Height - (PageSize.LETTER.Height - 20));
                overContent.ShowText("Page " + (i) + " of " + Pages);
                overContent.EndText();
                overContent.RestoreState();
            }
            stamper.Close();            
            return ms.ToArray();
        }
于 2014-03-10T19:07:00.317 に答える
0

私もこれに苦しんでいて、このライブラリも新しくしたので、これを試してみてください。多くの問題の後、コメントで述べたように、ロジックを2回適用しようとするだけで結果が得られました。

class PdfReportServlet extends HttpServlet
{
    public static int total = 0;

    public static int getTotal() 
    {
        return total;
    }

    public static void setTotal(int total) {
        PdfReportServlet .total = total;
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        String reportFor = request.getParameter("report");
        if(!"".equals(reportFor))
        {
            if(reportFor.equals("pdf"))
            {
    /* 
       from here logic starts
    */
                response.setContentType("application/pdf");
                Document document = new Document(PageSize.LETTER.rotate());
                try
                {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    PdfWriter pdfWriter = PdfWriter.getInstance(document, bos);
                    PdfReport pdfReport = new PdfReport();
                    pdfWriter.setPageEvent(pdfReport);
                    document.open();
                    String id = request.getParameter("id");
                    DettagliFamigliaPDFReport.generatePDFReport(document,id);
                    document.close();

                    /*
                     * now again give new references to Document and PdfWriter classes.
                     */

                    document = new Document(PageSize.LETTER.rotate());

                    pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());
                    PDFReport.setTotalPages(getTotal());/*##PAGES_TOTAL here i set total Pages which i get from above logic */
                    PdfReport pdfReport = new PdfReport();
                    pdfWriter.setPageEvent(pdfReport);
                    document.open();
                    id = request.getParameter("id");
                    PDFReport.generatePDFReport(document,id);
                    document.close();

                }
                catch(DocumentException de){
                    de.printStackTrace();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}


/*
    Here below i write the class inherits the PdfPageEventHelper class and also having generatePDFReport() method.
*/


public class PDFReport extends PdfPageEventHelper
{
    public static PdfTemplate template;
    public static int totalPages=0;

    public static int getTotalPages() {
        return totalPages;
    }

    public static void setTotalPages(int totalPages) {
        DettagliFamigliaPDFReport.totalPages = totalPages;
    }


    public static void generatePDFReport(Document document,String id)
    {
        // here your data to write on page of pdf.
    }

    @Override
    public void onOpenDocument(PdfWriter writer, Document doc) 
    {
        template = writer.getDirectContent().createTemplate(100, 100);
    }

    int totalPage = 0;
    @Override
    public void onCloseDocument(PdfWriter writer, Document doc) 
    {
        totalPage = writer.getPageNumber() - 1;/* at the end this method calls and you will get total number of pages.*/
        PdfReportServlet.setTotal(totalPage); /* while first time logic of servlet executes then i set the total pages to servlet's variable using this logic.
and second time servlet's logic is executing i passed totalPages to this class variable
where i marked ##PAGES_TOTAL  */
    }

    @Override
    public void onStartPage(PdfWriter writer, Document doc) {
        // Here i write header logic when each time page starts.
    }

    @Override`enter code here`
    public void onEndPage(PdfWriter writer, Document doc) 
    {
        Rectangle rect = writer.getPageSize();
        float width = rect.getWidth()/2;   

        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();

        String footerOne = "This document is printed on date "+dateFormat.format(date)+" - Page. "+writer.getPageNumber()+" of "+getTotalPages();

        Paragraph paraOne = new Paragraph(footerOne);

        Font fontFooter = new Font();
        fontFooter.setSize(8);
        fontFooter.setColor(Color.gray);

        paraOne.setFont(fontFooter);

        Phrase footerPhraseOne = new Phrase(paraOne);
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, footerPhraseOne,
                width, 30, 0);
    }
}
于 2014-01-22T14:20:36.513 に答える