以下代码用于水印pdf:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WaterDocument
{
class Program
{
static void Main(string[] args)
{
string FileLocation = "C:\\Users\\Desktop\\Hello.pdf";
// string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(FileLocation);
using (FileStream fs = new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetUnderContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(
BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.25f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.BLACK);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Confidential", rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
// Close the layer
cb.EndLayer();
}
stamper.Close();
}
File.Delete(FileLocation); //error on this line
File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);
}
}
}
在这一行我收到错误
File.Delete(FileLocation);
它给我发了以下错误
该进程无法访问文件“C:\ Users \ Desktop \ Hello.pdf”,因为它正由另一个进程使用。 请帮我在代码中找到问题。
答案 0 :(得分:2)
你没有在PdfReader对象reader1上调用Close,在File.Delete调用之前添加它:
reader1.Close()
您还应考虑在此行后添加大括号:
using (FileStream fs = new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create))
您可能会直接在该行下方添加一行,并且您的代码将停止工作,因为using语句将直接在下面的行中终止。