我制作了一个应用程序,允许特定用户从他的设备中选择PDF文件并在其上放置页码。 之后,该文件将在特定目录中显示为“ PDF.pdf”
但是我的问题是文件会占用大量内存,从而导致应用程序崩溃。
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
private string theFile = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
byte[] bytes = File.ReadAllBytes(theFile);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, 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++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(@"C:\Users\user\Pictures\Camera Roll\PDF.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
}
}
我试图将字节更改为其他方法,例如int。 但是正如你猜到的那样,它是行不通的。
答案 0 :(得分:3)
要扩展先前的注释-基本上,停止尝试将整个文件作为连续数组保存在内存中-该API基于Stream
,并且您可以使用FileStream
,因此:< / p>
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12,
iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (Stream source = File.OpenRead(theFile))
using (Stream dest = File.Create(@"C:\Users\user\Pictures\Camera Roll\PDF.pdf"))
{
PdfReader reader = new PdfReader(source);
using (PdfStamper stamper = new PdfStamper(reader, dest))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT,
new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
}
我无法从此处进行测试,但它看起来似乎可以正常工作。
基于快速搜索,它可能也可以用作:
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12,
iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (Stream dest = File.Create(@"C:\Users\user\Pictures\Camera Roll\PDF.pdf"))
{
PdfReader reader = new PdfReader(theFile);
// ...