使用itextsharp在pdf文件中的每个页面的标题中添加带有文本的图像

时间:2016-11-24 13:43:02

标签: c# itext

当我们使用下面的代码时,它只添加一个图像。是否有任何其他选项可以添加图像&每页都有文字?

private void AddHeader(string filephysicalpath,string nfile)         {             byte [] bytes = System.IO.File.ReadAllBytes(filephysicalpath);             String path = ConfigurationManager.AppSettings [" Documentheader"]。ToString()+ Session [" headerImg"];             Stream inputImageStream = new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read);

        Font blackFont = FontFactory.GetFont("Arial", 12, Font.BOLD, BaseColor.BLACK);
        using (MemoryStream stream = new MemoryStream())
        {
            PdfReader reader = new PdfReader(bytes);
            using (PdfStamper stamper = new PdfStamper(reader, stream))
            {
                int pages = reader.NumberOfPages;

                for (int i = 1; i <= pages; i++)
                {
                    string footer = Convert.ToString(Session["Footer"]);
                    if (Session["Footer"] != null)
                    {
                        // Phrase ft = new Phrase(footer, blackFont);
                        float marginLR = 36;
                        float marginB = 2;
                        float footerHeight = 10;
                        Rectangle pagesize = reader.GetCropBox(i);
                        if (pagesize == null)
                        {
                            pagesize = reader.GetPageSize(i);
                        }
                        Rectangle rect = new Rectangle(
                                pagesize.Left + marginLR, pagesize.Top + marginB,
                                pagesize.Right - marginLR, pagesize.Top + marginB + footerHeight
                            );



                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                        image.SetAbsolutePosition(rect.Left, rect.Top - image.ScaledHeight);
                        var pdfContentByte = stamper.GetOverContent(1);
                        pdfContentByte.AddImage(image);
                        inputImageStream.Seek(0L, SeekOrigin.Begin);
                        // ct.AddElement(new PdfPTableHeader (image));

                    }
                }
            }
            reader.Close();
            bytes = stream.ToArray();
        }
        System.IO.File.WriteAllBytes(filephysicalpath, bytes);
    }

2 个答案:

答案 0 :(得分:2)

在你的循环中你做

       var pdfContentByte = stamper.GetOverContent(1);
       pdfContentByte.AddImage(image);

即。您始终使用第1页的OverContent并将图像添加到其中。相反,您应该使用页面OverContent的{​​{1}}:

i

此外,您只应导入一次图像,即移动线

       var pdfContentByte = stamper.GetOverContent(i);
       pdfContentByte.AddImage(image);

在循环之上。

答案 1 :(得分:0)

您是否尝试在下次使用之前将inputImageStream设置为开始?

// file is the root directory of the segments.
private static void indexSegments(File file)
        throws IOException, IllegalAccessException, InstantiationException {
    // Do not try to index files that cannot be read.
    if (file.canRead() & file.isDirectory()) {
        // List with all the segments.
        File[] segmentDirs = file.listFiles();
        if (segmentDirs == null) {
            System.err.println("No segment directories found in '" +
                                file.getAbsolutePath() + "'");
            return;
        }
        Configuration conf = NutchConfiguration.create();
        FileSystem fs = FileSystem.get(conf);
        // Index all the segments.
        for (File segment : segmentDirs) {
            /* Only the content of the documents managed in
             * the segment is useful for the system. */
            String segmentData = segment.getAbsolutePath() + "/" +
                    Content.DIR_NAME + "/part-00000/data";
            if (!new File(segmentData).exists()) {
                System.out.println("Skipping segment: '" + segment.getName() +
                                   "': no data directory present.");
                continue;
            }
            SequenceFile.Reader reader =
                    new SequenceFile.Reader(fs, new Path(segmentData), conf);
            Writable key = (Writable) reader.getKeyClass().newInstance();
            // Index all the documents managed in the current segment.
            while (reader.next(key)) {
                Content content = new Content();
                reader.getCurrentValue(content);
                String url = key.toString();
                String baseName = FilenameUtils.getBaseName(url);
                String extension = FilenameUtils.getExtension(url);
                // Skips the document if it's not a XML file.
                String mimeType = new Tika().detect(content.getContent());
                if (mimeType == null | !mimeType.equals(MediaType.APPLICATION_XML.toString())) {
                    System.out.println("Skipping document: '" + baseName +
                                       "': not a XML file.");
                    continue;
                }
                /* Content of the document. */
                ByteArrayInputStream bas = new ByteArrayInputStream(content.getContent());
                int n = bas.available();
                byte[] bytes = new byte[n];
                bas.read(bytes, 0, n);
                bas.close();
                String docContent = new String(bytes, StandardCharsets.UTF_8);
                // TODO: Do what you want with the content.
            }
        }
    }
}

Meybe它的指针在流的末尾,下一个调用返回空图像?