1. 引用第三方itextsharp.dll文件
2. 前台页面设计
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
上传:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="UploadBtn" runat="server" Text="Upload"
οnclick="UploadBtn_Click" />
<br />
总页数:<asp:Label ID="TotalNumber" runat="server"></asp:Label><br />
起始页:<asp:TextBox ID="StartPage" runat="server"></asp:TextBox><br />
终止页:<asp:TextBox ID="EndPage" runat="server"></asp:TextBox><br />
拆分:
<asp:Button ID="Split" runat="server" Text="Split" OnClick="Split_Click" Width="96px" /><br />
</div>
</form>
</body>
</html>
3. 后台代码如下:
public partial class SplitPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
static string newFileName;
static string fileName = string.Empty;
static bool flag = false;
static PdfReader reader = null;
static int pdfNum = 0;
static string splitFileName = string.Empty;
// Upload the file
protected void Upload()
{
Random random = new Random();
int str = random.Next(4);
string strDate = DateTime.Now.ToString("yyyyMMddhhmmss") + str.ToString();
if (this.FileUpload1.HasFile)
{
int i = this.FileUpload1.FileName.LastIndexOf(".");
string extension = this.FileUpload1.FileName.Substring(i + 1);
if (extension.ToLower() == "pdf")
{
fileName = this.FileUpload1.FileName;
newFileName = strDate + fileName;
string filePath = Server.MapPath("~/SplitBefore/") + newFileName;
this.FileUpload1.SaveAs(filePath);
reader = new PdfReader(filePath);
pdfNum = reader.NumberOfPages;
Label1.Text = pdfNum.ToString();
flag = true;
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('Upload Success')</script>");
}
else
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "type", "<script>alert('File Type Error')</script>");
}
}
else
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "pdf", "<script>alert('Please choose a PDF file')</script>");
}
}
// Validate input number
protected bool ValidateInput()
{
Regex regex = new Regex(@"^\d+$");
if (regex.IsMatch(txtStartPage.Text) && regex.IsMatch(txtEndPage.Text))
{
if (int.Parse(txtEndPage.Text) < int.Parse(txtStartPage.Text))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "inputNum", "<script>alert('End Page should more than start page!');</script>");
return false;
}
else
{
return true;
}
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "error", "<script>alert('Input should be a mumber!');</script>");
return false;
}
}
// Split PDF
protected void Split()
{
if (flag == true)
{
if (ValidateInput())
{
int startPage = 1;
int endPage = pdfNum;
startPage = int.Parse(txtStartPage.Text);
endPage = int.Parse(txtEndPage.Text);
if (startPage < 1 || endPage > pdfNum)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "pageError", "<script>alert('Input Page Error!')</script>");
}
else
{
Document document = new Document(reader.GetPageSizeWithRotation(startPage));
string strNewDate = DateTime.Now.ToString("yyyyMMddhhmmss") + fileName;
splitFileName = "split" + strNewDate;
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/SplitAfter/" + splitFileName), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (startPage <= endPage)
{
document.SetPageSize(reader.GetPageSizeWithRotation(startPage));
document.NewPage();
page = writer.GetImportedPage(reader, startPage);
rotation = reader.GetPageRotation(startPage);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(startPage).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
startPage++;
}
document.Close();
lb.Text = splitFileName;
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ss", "<script>alert('Split Success')</script>");
txtStartPage.Text = string.Empty;
txtEndPage.Text = string.Empty;
flag = false;
reader = null;
}
}
}
else
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "upload", "<script>alert('Please upload pdf first')</script>");
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Upload();
}
protected void btnSplit_Click(object sender, EventArgs e)
{
Split();
}
protected void lb_Click(object sender, EventArgs e)
{
Process.Start(Server.MapPath("~/SplitAfter/" + splitFileName));
}
}
4. 由于FileUpload只支持4MB文件,因此需要在Web.Config
<httpRuntime maxRequestLength="400000" executionTimeout="3600"/>
</system.web>
合并PDF核心代码:
protected void MergePDFFiles(string[] fileList, string outMergeFile)
{
PdfReader reader;
Document document = new Document();
// Define the output place, and add the document to the stream
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
// Open document
document.Open();
// PDF ContentByte
PdfContentByte cb = writer.DirectContent;
// PDF import page
PdfImportedPage newPage;
for (int i = 0; i < fileList.Length; i++)
{
reader = new PdfReader(fileList[i]);
int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
cb.AddTemplate(newPage, 0, 0);
}
}
document.Close();
}