本文整理汇总了C#中iTextSharp.text.pdf.PdfStamper类的典型用法代码示例。如果您正苦于以下问题:C# PdfStamper类的具体用法?C# PdfStamper怎么用?C# PdfStamper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PdfStamper类属于iTextSharp.text.pdf命名空间,在下文中一共展示了PdfStamper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DoGet
// ---------------------------------------------------------------------------
/**
* Show keys and values passed to the query string with GET
*/
protected void DoGet(byte[] pdf, Stream stream) {
// We get a resource from our web app
PdfReader reader = new PdfReader(pdf);
// Now we create the PDF
using (PdfStamper stamper = new PdfStamper(reader, stream)) {
// We add a submit button to the existing form
PushbuttonField button = new PushbuttonField(
stamper.Writer, new Rectangle(90, 660, 140, 690), "submit"
);
button.Text = "POST";
button.BackgroundColor = new GrayColor(0.7f);
button.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
PdfFormField submit = button.Field;
submit.Action = PdfAction.CreateSubmitForm(
WebContext.Request.RawUrl, null, 0
);
stamper.AddAnnotation(submit, 1);
// We add an extra field that can be used to upload a file
TextField file = new TextField(
stamper.Writer, new Rectangle(160, 660, 470, 690), "image"
);
file.Options = TextField.FILE_SELECTION;
file.BackgroundColor = new GrayColor(0.9f);
PdfFormField upload = file.GetTextField();
upload.SetAdditionalActions(PdfName.U,
PdfAction.JavaScript(
"this.getField('image').browseForFileToSubmit();"
+ "this.getField('submit').setFocus();",
stamper.Writer
)
);
stamper.AddAnnotation(upload, 1);
}
}
示例2: Write
// ---------------------------------------------------------------------------
public void Write(Stream stream)
{
using (ZipFile zip = new ZipFile())
{
Stationery s = new Stationery();
StampStationery ss = new StampStationery();
byte[] stationery = s.CreateStationary();
byte[] sStationery = ss.ManipulatePdf(
ss.CreatePdf(), stationery
);
byte[] insertPages = ManipulatePdf(sStationery, stationery);
zip.AddEntry(RESULT1, insertPages);
// reorder the pages in the PDF
PdfReader reader = new PdfReader(insertPages);
reader.SelectPages("3-41,1-2");
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
}
zip.AddEntry(RESULT2, ms.ToArray());
}
zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationery);
zip.AddEntry(Utility.ResultFileName(ss.ToString() + ".pdf"), sStationery);
zip.Save(stream);
}
}
示例3: DecryptFile
internal Boolean DecryptFile(
string inputFile,
string outputFile,
IEnumerable<string> userPasswords)
{
foreach (var pwd in userPasswords)
{
try
{
using (var reader = new PdfReader(inputFile, new ASCIIEncoding().GetBytes(pwd)))
{
reader.GetType().Field("encrypted").SetValue(reader, false);
using (var outStream = File.OpenWrite(outputFile))
{
using (var stamper = new PdfStamper(reader, outStream))
{
stamper.Close();
}
}
}
return true;
}
catch (Exception ex)
{
Logger.ErrorFormat(ex, "Error trying to decrypt file {0}: {1}", inputFile, ex.Message);
}
}
return false;
}
示例4: Write
// ---------------------------------------------------------------------------
public virtual void Write(Stream stream) {
using (ZipFile zip = new ZipFile()) {
// Get the movies
IEnumerable<Movie> movies = PojoFactory.GetMovies();
string datasheet = Path.Combine(Utility.ResourcePdf, DATASHEET);
string className = this.ToString();
// Fill out the data sheet form with data
foreach (Movie movie in movies) {
if (movie.Year < 2007) continue;
PdfReader reader = new PdfReader(datasheet);
string dest = string.Format(RESULT, movie.Imdb);
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
AcroFields fields = stamper.AcroFields;
fields.GenerateAppearances = true;
Fill(fields, movie);
if (movie.Year == 2007) stamper.FormFlattening = true;
}
zip.AddEntry(dest, ms.ToArray());
}
}
zip.AddFile(datasheet, "");
zip.Save(stream);
}
}
示例5: WatermarkPDF_SN
public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
{
try
{
PdfReader reader = new PdfReader(SourcePdfPath);
PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
int n = reader.NumberOfPages;
int i = 0;
PdfContentByte under;
iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
im.SetAbsolutePosition(positionX, positionY);
im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
while (i < n)
{
i++;
under = stamp.GetUnderContent(i);
under.AddImage(im, true);
}
stamp.Close();
reader.Close();
}
catch (Exception ex)
{
msg = ex.Message;
return false;
}
msg = "��ˮӡ�ɹ���";
return true;
}
示例6: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src with the file dest as result
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src) {
// Create a table with named actions
Font symbol = new Font(Font.FontFamily.SYMBOL, 20);
PdfPTable table = new PdfPTable(4);
table.DefaultCell.Border = Rectangle.NO_BORDER;
table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
Chunk first = new Chunk( ((char)220).ToString() , symbol);
first.SetAction(new PdfAction(PdfAction.FIRSTPAGE));
table.AddCell(new Phrase(first));
Chunk previous = new Chunk( ((char)172).ToString(), symbol);
previous.SetAction(new PdfAction(PdfAction.PREVPAGE));
table.AddCell(new Phrase(previous));
Chunk next = new Chunk( ((char)174).ToString(), symbol);
next.SetAction(new PdfAction(PdfAction.NEXTPAGE));
table.AddCell(new Phrase(next));
Chunk last = new Chunk( ((char)222).ToString(), symbol);
last.SetAction(new PdfAction(PdfAction.LASTPAGE));
table.AddCell(new Phrase(last));
table.TotalWidth = 120;
// Create a reader
PdfReader reader = new PdfReader(src);
using (MemoryStream ms = new MemoryStream()) {
// Create a stamper
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
// Add the table to each page
PdfContentByte canvas;
for (int i = 0; i < reader.NumberOfPages; ) {
canvas = stamper.GetOverContent(++i);
table.WriteSelectedRows(0, -1, 696, 36, canvas);
}
}
return ms.ToArray();
}
}
示例7: Open
/// <summary>
/// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
/// </summary>
public static PdfDocument Open(MemoryStream sourceStream, string password = null)
{
PdfDocument outDoc;
sourceStream.Position = 0;
var mode = PdfDocumentOpenMode.Modify;
try
{
outDoc = PdfReader.Open(sourceStream, mode);
}
catch (PdfReaderException)
{
sourceStream.Position = 0;
var outputStream = new MemoryStream();
var reader = password == null ?
new TextSharp.PdfReader(sourceStream) :
new TextSharp.PdfReader(sourceStream, Encoding.UTF8.GetBytes(password));
var pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream) { FormFlattening = true };
pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
pdfStamper.Writer.CloseStream = false;
pdfStamper.Close();
outDoc = PdfReader.Open(outputStream, mode);
}
return outDoc;
}
示例8: llenarFormulario
//Permite cargar en un PDF información en los formularios preestablecidos.
public void llenarFormulario(string archivoOrigen, string archivoFinal, string dato)
{
//Establece el archivo de entrada y de salida.
string pdfTemplate = archivoOrigen;
string newFile = archivoFinal;
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.OpenOrCreate));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// Asigna los campos
pdfFormFields.SetField("Colono", dato);
//Muestra mensaje.
//MessageBox.Show(sTmp, "Terminado");
// Cambia la propiedad para que no se pueda editar el PDF
pdfStamper.FormFlattening = true;
pdfStamper.FreeTextFlattening = true;
pdfStamper.Writer.CloseStream = true;
pdfStamper.Close();
// Cierra el PDF
pdfStamper.Close();
pdfReader.Close();
}
示例9: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src) {
PdfReader reader = new PdfReader(src);
PdfObject obj;
PdfDictionary action;
for (int i = 1; i < reader.XrefSize; i++) {
obj = reader.GetPdfObject(i);
if (obj is PdfDictionary) {
action = ((PdfDictionary)obj).GetAsDict(PdfName.A);
if (action == null) continue;
if (PdfName.LAUNCH.Equals(action.GetAsName(PdfName.S))) {
action.Remove(PdfName.F);
action.Remove(PdfName.WIN);
action.Put(PdfName.S, PdfName.JAVASCRIPT);
action.Put(PdfName.JS, new PdfString(
"app.alert('Launch Application Action removed by iText');\r"
));
}
}
}
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
}
return ms.ToArray();
}
}
示例10: Create
public async Task<byte[]> Create(Invoice invoice)
{
var formBytes = await GetInvoiceFormAsync();
byte[] output = null;
using (var rdr = new PdfReader(formBytes))
{
var outputStream = new MemoryStream();
using (var stamper = new PdfStamper(rdr, outputStream))
{
stamper.FormFlattening = true;
stamper.AcroFields.SetField("StartDate", invoice.StartDateTime.ToString("yyyy-MM-dd"));
stamper.AcroFields.SetField("EndAddress", invoice.EndAddress);
stamper.AcroFields.SetField("StartAddress", invoice.StartAddress);
stamper.AcroFields.SetField("Cost", invoice.Cost.ToString());
stamper.AcroFields.SetField("Distance", String.Format("{0} miles", invoice.Distance.ToString()));
stamper.AcroFields.SetField("Duration", String.Format("{0}''", invoice.Duration.ToString()));
stamper.AcroFields.SetField("EmployeeName", invoice.EmployeeName);
stamper.AcroFields.SetField("SignatureName", invoice.EmployeeName);
stamper.AcroFields.SetField("StartTime", invoice.StartDateTime.ToString("HH:mm:ss tt"));
stamper.AcroFields.SetField("Signature", Convert.ToBase64String(invoice.Signature));
}
output = (Byte[])outputStream.ToArray();
}
return output;
}
示例11: RenameFieldsIn
// ---------------------------------------------------------------------------
/**
* Renames the fields in an interactive form.
* @param datasheet the path to the original form
* @param i a number that needs to be appended to the field names
* @return a byte[] containing an altered PDF file
*/
private static byte[] RenameFieldsIn(string datasheet, int i)
{
List<string> form_keys = new List<string>();
using (var ms = new MemoryStream())
{
PdfReader reader = new PdfReader(datasheet);
// Create the stamper
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
// Get the fields
AcroFields form = stamper.AcroFields;
// so we aren't hit with 'Collection was modified' exception
foreach (string k in stamper.AcroFields.Fields.Keys)
{
form_keys.Add(k);
}
// Loop over the fields
foreach (string key in form_keys)
{
// rename the fields
form.RenameField(key, string.Format("{0}_{1}", key, i));
}
}
reader.Close();
return ms.ToArray();
}
}
示例12: WritePDF
public static void WritePDF(string outFilename, Dictionary<string, string> keys)
{
using (var existingFileStream = new FileStream(DefaultTemplatePath, FileMode.Open))
using (var newFileStream = new FileStream(outFilename, FileMode.Create))
{
var pdfReader = new PdfReader(existingFileStream);
var stamper = new PdfStamper(pdfReader, newFileStream);
try
{
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
//File.WriteAllLines(@"fields.txt", fieldKeys.OfType<string>().ToArray());
foreach (string fieldKey in fieldKeys)
{
if (keys.ContainsKey(fieldKey))
{
form.SetField(fieldKey, keys[fieldKey]);
}
}
stamper.FormFlattening = true;
}
finally
{
stamper.Close();
pdfReader.Close();
}
}
}
示例13: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src with the file dest as result
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src)
{
// Create a list with bookmarks
List<Dictionary<string, object>> outlines =
new List<Dictionary<string, object>>();
Dictionary<string, object> map = new Dictionary<string, object>();
outlines.Add(map);
map.Add("Title", "Calendar");
List<Dictionary<string, object>> kids =
new List<Dictionary<string, object>>();
map.Add("Kids", kids);
int page = 1;
IEnumerable<string> days = PojoFactory.GetDays();
foreach (string day in days)
{
Dictionary<string, object> kid = new Dictionary<string, object>();
kids.Add(kid);
kid["Title"] = day;
kid["Action"] = "GoTo";
kid["Page"] = String.Format("{0} Fit", page++);
}
// Create a reader
PdfReader reader = new PdfReader(src);
using (MemoryStream ms = new MemoryStream())
{
// Create a stamper
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
stamper.Outlines = outlines;
}
return ms.ToArray();
}
}
示例14: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src with the file dest as result
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src)
{
// Create the reader
PdfReader reader = new PdfReader(src);
int n = reader.NumberOfPages;
using (MemoryStream ms = new MemoryStream())
{
// Create the stamper
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
// Make a list with all the possible actions
actions = new List<PdfAction>();
PdfDestination d;
for (int i = 0; i < n; )
{
d = new PdfDestination(PdfDestination.FIT);
actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer));
}
// Add a navigation table to every page
PdfContentByte canvas;
for (int i = 0; i < n; )
{
canvas = stamper.GetOverContent(++i);
CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas);
}
}
return ms.ToArray();
}
}
示例15: FillForm
public void FillForm(
Dictionary<string, string> items,
Stream formStream)
{
PdfStamper pdfStamper = new PdfStamper(pdfReader, formStream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
BaseFont arialBaseFont;
string arialFontPath;
try
{
arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
catch (IOException)
{
arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
pdfFormFields.AddSubstitutionFont(arialBaseFont);
foreach (KeyValuePair<string, string> item in items)
{
pdfFormFields.SetFieldProperty(item.Key, "textfont", arialBaseFont, null);
if (item.Value!=null) pdfFormFields.SetField(item.Key, item.Value);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}