public static void Run() { // ExStart:TextinFooter // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir + "TextinFooter.pdf"); // Create footer TextStamp textStamp = new TextStamp("Footer Text"); // Set properties of the stamp textStamp.BottomMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Bottom; // Add footer on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } dataDir = dataDir + "TextinFooter_out_.pdf"; //save updated PDF file pdfDocument.Save(dataDir); // ExEnd:TextinFooter Console.WriteLine("\nText in footer added successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:AddTextStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir+ "AddTextStamp.pdf"); // Create text stamp TextStamp textStamp = new TextStamp("Sample Stamp"); // Set whether stamp is background textStamp.Background = true; // Set origin textStamp.XIndent = 100; textStamp.YIndent = 100; // Rotate stamp textStamp.Rotate = Rotation.on90; // Set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 14.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.FontStyle = FontStyles.Italic; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); // Add stamp to particular page pdfDocument.Pages[1].AddStamp(textStamp); dataDir = dataDir + "AddTextStamp_out.pdf"; // Save output document pdfDocument.Save(dataDir); // ExEnd:AddTextStamp Console.WriteLine("\nText stamp added successfully.\nFile saved at " + dataDir); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Instantiate Document object with input file Document doc = new Document(dataDir+ "DefineAlignment.pdf"); // instantiate FormattedText object with sample string FormattedText text = new FormattedText("This"); // add new text line to FormattedText text.AddNewLineText("is sample"); text.AddNewLineText("Center Aligned"); text.AddNewLineText("TextStamp"); text.AddNewLineText("Object"); // create TextStamp object using FormattedText TextStamp stamp = new TextStamp(text); // specify the Horizontal Alignment of text stamp as Center aligned stamp.HorizontalAlignment = HorizontalAlignment.Center; // specify the Vertical Alignment of text stamp as Center aligned stamp.VerticalAlignment = VerticalAlignment.Center; // specify the Text Horizontal Alignment of TextStamp as Center aligned stamp.TextAlignment = HorizontalAlignment.Center; // set top margin for stamp object stamp.TopMargin = 20; // add the stamp object over first page of document doc.Pages[1].AddStamp(stamp); // save the udpated document doc.Save(dataDir+ "StampedPDF.pdf"); }
public static void Run() { // ExStart:AddTextStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir + "AddTextStamp.pdf"); // Create text stamp TextStamp textStamp = new TextStamp("Sample Stamp"); // Set whether stamp is background textStamp.Background = true; // Set origin textStamp.XIndent = 100; textStamp.YIndent = 100; // Rotate stamp textStamp.Rotate = Rotation.on90; // Set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 14.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.FontStyle = FontStyles.Italic; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); // Add stamp to particular page pdfDocument.Pages[1].AddStamp(textStamp); dataDir = dataDir + "AddTextStamp_out_.pdf"; // Save output document pdfDocument.Save(dataDir); // ExEnd:AddTextStamp Console.WriteLine("\nText stamp added successfully.\nFile saved at " + dataDir); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Instantiate Document object with input file Document doc = new Document(dataDir + "DefineAlignment.pdf"); // instantiate FormattedText object with sample string FormattedText text = new FormattedText("This"); // add new text line to FormattedText text.AddNewLineText("is sample"); text.AddNewLineText("Center Aligned"); text.AddNewLineText("TextStamp"); text.AddNewLineText("Object"); // create TextStamp object using FormattedText TextStamp stamp = new TextStamp(text); // specify the Horizontal Alignment of text stamp as Center aligned stamp.HorizontalAlignment = HorizontalAlignment.Center; // specify the Vertical Alignment of text stamp as Center aligned stamp.VerticalAlignment = VerticalAlignment.Center; // specify the Text Horizontal Alignment of TextStamp as Center aligned stamp.TextAlignment = HorizontalAlignment.Center; // set top margin for stamp object stamp.TopMargin = 20; // add the stamp object over first page of document doc.Pages[1].AddStamp(stamp); // save the udpated document doc.Save(dataDir + "StampedPDF.pdf"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); //open document Document pdfDocument = new Document(dataDir+ "TextinHeader.pdf"); //create header TextStamp textStamp = new TextStamp("Header Text"); //set properties of the stamp textStamp.TopMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Top; //add header on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } //save updated document pdfDocument.Save(dataDir+ "TextinHeader_out.pdf"); }
public static void Run() { // ExStart:TextinFooter // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir+ "TextinFooter.pdf"); // Create footer TextStamp textStamp = new TextStamp("Footer Text"); // Set properties of the stamp textStamp.BottomMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Bottom; // Add footer on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } dataDir = dataDir + "TextinFooter_out.pdf"; // Save updated PDF file pdfDocument.Save(dataDir); // ExEnd:TextinFooter Console.WriteLine("\nText in footer added successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:DefineAlignment // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Instantiate Document object with input file Document doc = new Document(dataDir+ "DefineAlignment.pdf"); // Instantiate FormattedText object with sample string FormattedText text = new FormattedText("This"); // Add new text line to FormattedText text.AddNewLineText("is sample"); text.AddNewLineText("Center Aligned"); text.AddNewLineText("TextStamp"); text.AddNewLineText("Object"); // Create TextStamp object using FormattedText TextStamp stamp = new TextStamp(text); // Specify the Horizontal Alignment of text stamp as Center aligned stamp.HorizontalAlignment = HorizontalAlignment.Center; // Specify the Vertical Alignment of text stamp as Center aligned stamp.VerticalAlignment = VerticalAlignment.Center; // Specify the Text Horizontal Alignment of TextStamp as Center aligned stamp.TextAlignment = HorizontalAlignment.Center; // Set top margin for stamp object stamp.TopMargin = 20; // Add the stamp object over first page of document doc.Pages[1].AddStamp(stamp); dataDir = dataDir + "StampedPDF_out.pdf"; // Save the udpated document doc.Save(dataDir); // ExEnd:DefineAlignment Console.WriteLine("\nAlignment defined successfully for text stamp.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir + "input.pdf"); //create text stamp TextStamp textStamp = new TextStamp("Sample Stamp"); //set whether stamp is background textStamp.Background = true; //set origin textStamp.XIndent = 100; textStamp.YIndent = 100; //rotate stamp textStamp.Rotate = Rotation.on90; //set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 14.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.FontStyle = FontStyles.Italic; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); //add stamp to particular page pdfDocument.Pages[1].AddStamp(textStamp); //save output document pdfDocument.Save(dataDir + "output.pdf"); }
public static void UsingTextStamp() { // ExStart:UsingTextStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create Document instance Document pdfDocument = new Document(); // Add page to pages collection of Document Page page = pdfDocument.Pages.Add(); // Instantiate TextStamp instance with sample text TextStamp stamp = new TextStamp("This is text stamp with character spacing"); // Specify font name for Stamp object stamp.TextState.Font = FontRepository.FindFont("Arial"); // Specify Font size for TextStamp stamp.TextState.FontSize = 12; // Specify character specing as 1f stamp.TextState.CharacterSpacing = 1f; // Set the XIndent for Stamp stamp.XIndent = 100; // Set the YIndent for Stamp stamp.YIndent = 500; // Add textual stamp to page instance stamp.Put(page); dataDir = dataDir + "CharacterSpacingUsingTextStamp_out_.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:UsingTextStamp Console.WriteLine("\nCharacter spacing specified successfully using text stamp.\nFile saved at " + dataDir); }
/// <summary> /// 浮水印跟頁面一樣大 /// </summary> /// <param name="pdfPage"></param> /// <param name="arg"></param> private static void AddWatermarkFitPage(Aspose.Pdf.Page pdfPage, WatermarkArg arg) { //var text = new FormattedText(arg.Watermark); var defaultTextState = new TextState("MingLiU"); var stamp = new TextStamp(arg.Watermark, defaultTextState); stamp.RotateAngle = arg.RotateAngle; stamp.XIndent = arg.WatermarkHorizontalSpace; stamp.YIndent = arg.WatermarkVerticalSpace; stamp.Opacity = arg.Opacity; stamp.Width = pdfPage.CropBox.Width; stamp.Height = pdfPage.CropBox.Height; pdfPage.AddStamp(stamp); }
private static void AddText(Page page, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, HeaderFooterConfig headerFooterConfig, string text, bool isHeader, Package package) { var pageMargin = GetHeaderFooterMargin(horizontalAlignment, headerFooterConfig, isHeader, package); TextStamp textStamp = new TextStamp(text) { TopMargin = pageMargin.TopPoints, BottomMargin = pageMargin.BottomPoints, LeftMargin = pageMargin.LeftPoints, RightMargin = pageMargin.RightPoints, HorizontalAlignment = horizontalAlignment, VerticalAlignment = verticalAlignment }; page.AddStamp(textStamp); }
public byte[] AddWatermarkPdf(string filePath, string stanName) { byte[] convertedToBytes; // Open document Document pdfDocument = new Document(filePath); var blankStr = " "; var textStr1 = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}", stanName, blankStr, stanName, blankStr, stanName, blankStr, stanName, blankStr, stanName, blankStr, stanName); var textStr2 = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}", blankStr, stanName, blankStr, stanName, blankStr, stanName, blankStr, stanName, blankStr, stanName, blankStr); // Add stamp to each page of PDF //foreach (Page page in pdfDocument.Pages) for (int i = 1; i <= pdfDocument.Pages.Count; i++) { for (int j = 1; j <= 15; j++) { // Create text stamp TextStamp textStamp; if (j % 2 == 0) { textStamp = new TextStamp(textStr2); } else { textStamp = new TextStamp(textStr1); } // Set origin textStamp.XIndent = 10; textStamp.YIndent = (j * 100) - 500; // Set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 30.0F; textStamp.TextState.FontStyle = FontStyles.Italic; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Gray); textStamp.Opacity = 50; textStamp.RotateAngle = 45; pdfDocument.Pages[i].AddStamp(textStamp); } } using (MemoryStream updatedImageMemorySteam = new MemoryStream()) { pdfDocument.Save(updatedImageMemorySteam, Aspose.Pdf.SaveFormat.Pdf); convertedToBytes = updatedImageMemorySteam.ToArray(); } return(convertedToBytes); }
public static void Run() { // ExStart:AddDateTimeStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir + "AddTextStamp.pdf"); string annotationText = string.Empty; annotationText = DateTime.Now.ToString("MM/dd/yy hh:mm:ss tt "); // Create text stamp TextStamp textStamp = new TextStamp(annotationText); // Set properties of the stamp textStamp.BottomMargin = 10; textStamp.RightMargin = 20; textStamp.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; textStamp.VerticalAlignment = VerticalAlignment.Bottom; // Adding stamp on stamp collection pdfDocument.Pages[1].AddStamp(textStamp); DefaultAppearance default_appearance = new DefaultAppearance("Arial", 6, System.Drawing.Color.Black); FreeTextAnnotation textAnnotation = new FreeTextAnnotation(pdfDocument.Pages[1], new Aspose.Pdf.Rectangle(0, 0, 0, 0), default_appearance); textAnnotation.Name = "Stamp"; textAnnotation.Accept(new AnnotationSelector(textAnnotation)); textAnnotation.Contents = textStamp.Value; // TextAnnotation.Open = true; // TextAnnotation.Icon = Aspose.Pdf.InteractiveFeatures.Annotations.TextIcon.Key; Border border = new Border(textAnnotation); border.Width = 0; border.Dash = new Dash(1, 1); textAnnotation.Border = border; textAnnotation.Rect = new Aspose.Pdf.Rectangle(0, 0, 0, 0); pdfDocument.Pages[1].Annotations.Add(textAnnotation); dataDir = dataDir + "AddDateTimeStamp_out.pdf"; // Save output document pdfDocument.Save(dataDir); // ExEnd:AddDateTimeStamp Console.WriteLine("\nDate time stamp added successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:AddDateTimeStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Open document Document pdfDocument = new Document(dataDir+ "AddTextStamp.pdf"); string annotationText = string.Empty; annotationText = DateTime.Now.ToString("MM/dd/yy hh:mm:ss tt "); // Create text stamp TextStamp textStamp = new TextStamp(annotationText); // Set properties of the stamp textStamp.BottomMargin = 10; textStamp.RightMargin = 20; textStamp.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; textStamp.VerticalAlignment = VerticalAlignment.Bottom; // Adding stamp on stamp collection pdfDocument.Pages[1].AddStamp(textStamp); DefaultAppearance default_appearance = new DefaultAppearance("Arial", 6, System.Drawing.Color.Black); FreeTextAnnotation textAnnotation = new FreeTextAnnotation(pdfDocument.Pages[1], new Aspose.Pdf.Rectangle(0, 0, 0, 0), default_appearance); textAnnotation.Name = "Stamp"; textAnnotation.Accept(new AnnotationSelector(textAnnotation)); textAnnotation.Contents = textStamp.Value; // TextAnnotation.Open = true; // TextAnnotation.Icon = Aspose.Pdf.InteractiveFeatures.Annotations.TextIcon.Key; Border border = new Border(textAnnotation); border.Width = 0; border.Dash = new Dash(1, 1); textAnnotation.Border = border; textAnnotation.Rect = new Aspose.Pdf.Rectangle(0, 0, 0, 0); pdfDocument.Pages[1].Annotations.Add(textAnnotation); dataDir = dataDir + "AddDateTimeStamp_out.pdf"; // Save output document pdfDocument.Save(dataDir); // ExEnd:AddDateTimeStamp Console.WriteLine("\nDate time stamp added successfully.\nFile saved at " + dataDir); }
private void AddText(DocumentInfo doc, string signatureText, string signatureTextColor) { var page = doc.PdfDocument.Pages[1]; // Create text stamp TextStamp textStamp = new TextStamp(getFormattedText(signatureText)); // Set whether stamp is background // textStamp.Background = true; textStamp.HorizontalAlignment = HorizontalAlignment.Right; textStamp.VerticalAlignment = VerticalAlignment.Bottom; textStamp.TextAlignment = HorizontalAlignment.Center; // Set origin //textStamp.XIndent = 100; //textStamp.YIndent = 100; // Rotate stamp //textStamp.Rotate = Rotation.on90; // Set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 50; textStamp.Width = page.PageInfo.Width / 3; if (signatureTextColor != "") { if (!signatureTextColor.StartsWith("#")) { signatureTextColor = "#" + signatureTextColor; } textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.ColorTranslator.FromHtml(signatureTextColor)); } else { textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); } page.AddStamp(textStamp); }
/// <summary> /// 依 浮水印 水平地蓋滿整個頁面 /// </summary> /// <param name="pdfPage"></param> /// <param name="arg"></param> private static void AddWatermarkRepeatHorizontal(Aspose.Pdf.Page pdfPage, WatermarkArg arg) { if (arg.WatermarkHeight < minValue) { throw new ArgumentException($"{nameof(arg.WatermarkHeight)} must greater than {minValue}"); } if (arg.WatermarkWidth < minValue) { throw new ArgumentException($"{nameof(arg.WatermarkWidth)} must greater than {minValue}"); } //var text = new FormattedText(arg.Watermark); var yIndent = pdfPage.CropBox.Height - arg.WatermarkHeight; var yLimit = 0 - (arg.WatermarkHeight + arg.WatermarkVerticalSpace); var pageWidth = pdfPage.CropBox.Width; var xIndent = 0d; while (yIndent > yLimit) { while (xIndent < pageWidth) { var defaultTextState = new TextState("MingLiU"); var stamp = new TextStamp(arg.Watermark, defaultTextState); stamp.RotateAngle = arg.RotateAngle; stamp.XIndent = xIndent; stamp.YIndent = yIndent; stamp.Opacity = arg.Opacity; stamp.Width = arg.WatermarkWidth; stamp.Height = arg.WatermarkHeight; pdfPage.AddStamp(stamp); xIndent += (arg.WatermarkWidth + arg.WatermarkHorizontalSpace); } xIndent = 0; var yIdentReduce = (arg.WatermarkHeight + arg.WatermarkVerticalSpace); yIndent -= yIdentReduce; } }
private void AddWatermarkToPage(double pWidth, double pHeight, Aspose.Pdf.Page pg, string sUserName, string sTextDate) { //try{ // DeleteExistingWatermarks(pg); //}catch { //} double alfaR = 30; double c = pWidth / pHeight; double alfa = Math.Atan(c); alfaR = (alfa * 180) / Math.PI; FormattedText wtext = new FormattedText("Confidential", new FontColor(220, 20, 60), new FontColor(255, 255, 255), Aspose.Pdf.Facades.FontStyle.HelveticaBold, EncodingType.Winansi, true, 35); wtext.AddNewLineText("Downloaded by"); wtext.AddNewLineText(sUserName.Length > 55 ? sUserName.Substring(0, 55) : sUserName); wtext.AddNewLineText(sTextDate.Length > 19 ? sTextDate.Substring(0, 19) : sTextDate); TextStamp wStamp = new TextStamp(wtext); wStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); wStamp.TextState.FontStyle = FontStyles.Bold; wStamp.TextState.FontSize = 35; wStamp.HorizontalAlignment = HorizontalAlignment.Center; wStamp.VerticalAlignment = VerticalAlignment.Center; wStamp.TextAlignment = HorizontalAlignment.Center; wStamp.Opacity = .15F; wStamp.RotateAngle = (float)(alfaR - 90); pg.AddStamp(wStamp); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir+ "input.pdf"); //create header TextStamp textStamp = new TextStamp("Header Text"); //set properties of the stamp textStamp.TopMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Top; //add header on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } //save updated document pdfDocument.Save(dataDir+ "output.pdf"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); //open document Document pdfDocument = new Document(dataDir + "TextinHeader.pdf"); //create header TextStamp textStamp = new TextStamp("Header Text"); //set properties of the stamp textStamp.TopMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Top; //add header on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } //save updated document pdfDocument.Save(dataDir + "TextinHeader_out.pdf"); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir + "input.pdf"); //create header TextStamp textStamp = new TextStamp("Header Text"); //set properties of the stamp textStamp.TopMargin = 10; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Top; //add header on all pages foreach (Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } //save updated document pdfDocument.Save(dataDir + "output.pdf"); }
public static void Run() { // ExStart:DefineAlignment // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks(); // Instantiate Document object with input file Document doc = new Document(dataDir + "DefineAlignment.pdf"); // Instantiate FormattedText object with sample string FormattedText text = new FormattedText("This"); // Add new text line to FormattedText text.AddNewLineText("is sample"); text.AddNewLineText("Center Aligned"); text.AddNewLineText("TextStamp"); text.AddNewLineText("Object"); // Create TextStamp object using FormattedText TextStamp stamp = new TextStamp(text); // Specify the Horizontal Alignment of text stamp as Center aligned stamp.HorizontalAlignment = HorizontalAlignment.Center; // Specify the Vertical Alignment of text stamp as Center aligned stamp.VerticalAlignment = VerticalAlignment.Center; // Specify the Text Horizontal Alignment of TextStamp as Center aligned stamp.TextAlignment = HorizontalAlignment.Center; // Set top margin for stamp object stamp.TopMargin = 20; // Add the stamp object over first page of document doc.Pages[1].AddStamp(stamp); dataDir = dataDir + "StampedPDF_out.pdf"; // Save the udpated document doc.Save(dataDir); // ExEnd:DefineAlignment Console.WriteLine("\nAlignment defined successfully for text stamp.\nFile saved at " + dataDir); }
public byte[] ToPDF() { var options = new HtmlLoadOptions { PageInfo = { Width = PageSize.A4.Width, Height = PageSize.A4.Height, Margin = { Top = 35, Bottom= 40, Right = 35, Left = 35 } } }; Func <string, string> getManifestResource = s => { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(s)) { using (var reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } }; }; Action <Document, string> addReportHeader = (pdf, title) => { var stamp = new TextStamp(title) { TopMargin = 15, LeftMargin = 25, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Opacity = 0.6f, }; stamp.TextState.FontSize = 8; foreach (Page page in pdf.Pages) { page.AddStamp(stamp); } }; Action <Document> addCompanyNameFooter = pdf => { var stampText = String.Format("Generated on {0}", DateTime.Now.ToString("M/d/yy - h:mm tt")); var companyStamp = new TextStamp(stampText) { BottomMargin = 15, LeftMargin = 25, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom, Opacity = 0.6f, }; companyStamp.TextState.FontSize = 8; foreach (Page page in pdf.Pages) { page.AddStamp(companyStamp); } }; Action <Document> addPageNumberFooter = pdf => { var pageStamp = new TextStamp("") { BottomMargin = 15, RightMargin = 25, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Bottom, Opacity = 0.6f, }; pageStamp.TextState.FontSize = 8; var pageCount = 1; foreach (Page page in pdf.Pages) { pageStamp.Value = "Page: " + pageCount++; page.AddStamp(pageStamp); } }; Action <Document> addDocumentInfo = pdf => { var d = new DocumentInfo(pdf) { Author = "First Bank of Valkyrie", CreationDate = DateTime.Now, Title = "First Bank of Valkyrie " + DocumentTitle, Subject = "First Bank of Valkyrie " + DocumentTitle }; }; Func <string, object, Document> createDocument = (template, model) => { var html = Platform.RazorEngine.Run(template, model); var buffer = Encoding.UTF8.GetBytes(html); var instream = new MemoryStream(buffer); return(new Document(instream, options)); }; var docs = new List <Document>(); var templateId = string.Format("GeneratedPDF_{0}", View); var modelTemplate = getManifestResource(View); Platform.RazorEngine.AddTemplate(templateId, modelTemplate); docs.Add(createDocument(templateId, this)); using (var doc = new Document()) { foreach (var d in docs) { doc.Pages.Add(d.Pages); } addReportHeader.Invoke(doc, ("First Bank of Valkyrie " + DocumentTitle).Trim()); addCompanyNameFooter.Invoke(doc); addPageNumberFooter.Invoke(doc); addDocumentInfo.Invoke(doc); var privilege = DocumentPrivilege.ForbidAll; privilege.ChangeAllowLevel = 1; privilege.AllowPrint = true; privilege.AllowCopy = true; var fileSecurity = new PdfFileSecurity(doc); fileSecurity.SetPrivilege(privilege); using (var outstream = new MemoryStream()) { doc.Save(outstream); return(outstream.GetBuffer()); } } }
///<Summary> /// AddTextStamp method to add text stamp ///</Summary> public Response AddTextStamp(string fileName, string folderName, string watermarkText, string outputType, string watermarkColor, string fontFamily = @"Arial", float fontSize = 14.0f, string fontStyle = null, double textAngle = 45) { return(ProcessTask(fileName, folderName, "." + outputType, false, false, delegate(string inFilePath, string outPath, string zipOutFolder) { // Open document Document pdfDocument = new Document(inFilePath); // Create text stamp TextStamp textStamp = new TextStamp(getFormattedText(watermarkText)); // Set whether stamp is background textStamp.Background = true; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Center; textStamp.TextAlignment = HorizontalAlignment.Center; // Set origin //textStamp.XIndent = 100; //textStamp.YIndent = 100; // Rotate stamp //textStamp.Rotate = Rotation.on90; textStamp.RotateAngle = textAngle; // Set text properties textStamp.TextState.Font = FontRepository.FindFont(fontFamily); textStamp.TextState.FontSize = fontSize; switch (fontStyle) { case "Bold": { textStamp.TextState.FontStyle = FontStyles.Bold; } break; case "Italic": { textStamp.TextState.FontStyle = FontStyles.Italic; } break; case "Regular": case null: { textStamp.TextState.FontStyle = FontStyles.Regular; } break; } if (watermarkColor != "") { if (!watermarkColor.StartsWith("#")) { watermarkColor = "#" + watermarkColor; } textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.ColorTranslator.FromHtml(watermarkColor)); } else { textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); } // Add Text stamp to all pages foreach (Pdf.Page page in pdfDocument.Pages) { page.AddStamp(textStamp); } // Save the document in PDF format. pdfDocument.Save(outPath, GetSaveFormat(outputType)); })); }
public static void UploadPic(List <shap> shapes, string filename, string aspectRatio) { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //Create image stamp ImageStamp imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png")); for (int i = 0; i < shapes.Count; i++) { //create stamp Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); float shapeX = (shapes[i].x * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeY = (shapes[i].y * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeW = (shapes[i].w * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeH = (shapes[i].h * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); double yaxis = (float)(doc.Pages[shapes[i].p].Rect.URY - (shapeH + shapeY)); var isSpecial = true;//regexItem.IsMatch(shapes[i].imName); if (shapes[i].Itype == "highlight" || shapes[i].Itype == "image") { if (shapes[i].Itype == "highlight") { imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png")); } else { imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("Images/" + shapes[i].imName)); } imageStamp.Background = false; imageStamp.XIndent = (float)(shapeX); imageStamp.YIndent = (float)(yaxis); imageStamp.Height = shapeH; imageStamp.Width = shapeW; //Add stamp to particular page doc.Pages[shapes[i].p].AddStamp(imageStamp); } else if (shapes[i].Itype == "text") { /* * // create TextBuilder for first page * TextBuilder tb = new TextBuilder(doc.Pages[shapes[i].p]); * * // TextFragment with sample text * TextFragment fragment = new TextFragment(shapes[i].t); * * // set the font for TextFragment * fragment.TextState.Font = FontRepository.FindFont(shapes[i].n); * fragment.TextState.FontSize = Convert.ToInt32(shapes[i].s); * if (shapes[i].wt == "bold") * { * fragment.TextState.FontStyle = FontStyles.Bold; * } * * if (shapes[i].st == "italic") * { * fragment.TextState.FontStyle = FontStyles.Italic; * } * * // set the formatting of text as Underline * // fragment.TextState.Underline = true; * fragment.TextState.ForegroundColor = GetColor(shapes[i].c); * // specify the position where TextFragment needs to be placed * fragment.Position = new Position((float)(shapeX), (float)(yaxis)); * * // fragment.Rectangle.Rotate((360 - (Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI); * * // append TextFragment to PDF file * tb.AppendText(fragment); */ //create text stamp TextStamp textStamp = new TextStamp(shapes[i].t); //set whether stamp is background // textStamp.Background = true; //set origin textStamp.XIndent = (float)(shapeX); textStamp.YIndent = (float)(yaxis); //rotate stamp textStamp.RotateAngle = 360 - ((Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI); //set text properties textStamp.TextState.Font = FontRepository.FindFont(shapes[i].n); textStamp.TextState.FontSize = Convert.ToInt32(shapes[i].s) * 0.75f; if (shapes[i].wt == "bold") { textStamp.TextState.FontStyle = FontStyles.Bold; } if (shapes[i].st == "italic") { textStamp.TextState.FontStyle = FontStyles.Italic; } textStamp.TextState.ForegroundColor = GetColor(shapes[i].c); //add stamp to particular page doc.Pages[shapes[i].p].AddStamp(textStamp); } else if (shapes[i].Itype == "field" && isSpecial) { if (shapes[i].fieldType == "Text") { // Get a field TextBoxField textBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as TextBoxField; // Modify field value textBoxField.Value = shapes[i].t; } else if (shapes[i].fieldType == "CheckBox") { // Get a field CheckboxField checkBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as CheckboxField; if (shapes[i].t != "") { // Modify field value checkBoxField.Checked = Convert.ToBoolean(shapes[i].t); } } else if (shapes[i].fieldType == "Radio") { RadioButtonOptionField field = (RadioButtonOptionField)doc.Form.Fields[Convert.ToInt32(shapes[i].imName)]; RadioButtonField rbf = (RadioButtonField)field.Parent; if (Convert.ToBoolean(shapes[i].t)) { rbf.Selected = rbf.Options[field.OptionName].Index; } else { field.ActiveState = "Off"; } } else if (shapes[i].fieldType == "ComboBox") { // Get a field ComboBoxField comboBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as ComboBoxField; var values = shapes[i].t.Split(new string[] { "^^^" }, StringSplitOptions.None)[0]; foreach (var item in comboBoxField.Options.Cast <Option>()) { if (item.Value == values) { comboBoxField.Selected = item.Index; } } } } } doc.Save(HttpContext.Current.Server.MapPath("Convert/Export.pdf")); }
public IHttpActionResult UploadPic(UploadPicModel uploadPicModel) { var fullPath = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", uploadPicModel.documentId); var downloadFileName = "document.pdf"; var documentFileName = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", uploadPicModel.documentId, downloadFileName); Document doc = new Document(documentFileName); //Create image stamp ImageStamp imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("/img/Test.png")); for (int i = 0; i < uploadPicModel.shapes.Count; i++) { //create stamp Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); float shapeX = (uploadPicModel.shapes[i].x * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio); float shapeY = (uploadPicModel.shapes[i].y * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio); float shapeW = (uploadPicModel.shapes[i].w * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio); float shapeH = (uploadPicModel.shapes[i].h * 72 / 150) / (float)Convert.ToDouble(uploadPicModel.shapes[i].ratio); double yaxis = (float)(doc.Pages[uploadPicModel.shapes[i].p].Rect.URY - (shapeH + shapeY)); var isSpecial = true; //regexItem.IsMatch(uploadPicModel.shapes[i].imName); if (uploadPicModel.shapes[i].Itype == "highlight" || uploadPicModel.shapes[i].Itype == "image") { imageStamp = uploadPicModel.shapes[i].Itype == "highlight" ? new ImageStamp(HttpContext.Current.Server.MapPath("/img/test.png")) : new ImageStamp(fullPath + uploadPicModel.shapes[i].imName); imageStamp.Background = false; imageStamp.XIndent = (float)(shapeX); imageStamp.YIndent = (float)(yaxis); imageStamp.Height = shapeH; imageStamp.Width = shapeW; //Add stamp to particular page doc.Pages[uploadPicModel.shapes[i].p].AddStamp(imageStamp); } else if (uploadPicModel.shapes[i].Itype == "text") { //create text stamp TextStamp textStamp = new TextStamp(uploadPicModel.shapes[i].t); textStamp.XIndent = (float)(shapeX); textStamp.YIndent = (float)(yaxis); //rotate stamp textStamp.RotateAngle = 360 - (Convert.ToDouble(uploadPicModel.shapes[i].fieldType) * 180 / Math.PI); //set text properties textStamp.TextState.Font = FontRepository.FindFont(uploadPicModel.shapes[i].n); textStamp.TextState.FontSize = Convert.ToInt32(uploadPicModel.shapes[i].s) * 0.75f; if (uploadPicModel.shapes[i].wt == "bold") { textStamp.TextState.FontStyle = FontStyles.Bold; } if (uploadPicModel.shapes[i].st == "italic") { textStamp.TextState.FontStyle = FontStyles.Italic; } textStamp.TextState.ForegroundColor = GetColor(uploadPicModel.shapes[i].c); //add stamp to particular page doc.Pages[uploadPicModel.shapes[i].p].AddStamp(textStamp); } else if (uploadPicModel.shapes[i].Itype == "field" && isSpecial) { if (uploadPicModel.shapes[i].fieldType == "Text") { // Get a field TextBoxField textBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as TextBoxField; // Modify field value textBoxField.Value = uploadPicModel.shapes[i].t; } else if (uploadPicModel.shapes[i].fieldType == "CheckBox") { // Get a field CheckboxField checkBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as CheckboxField; if (uploadPicModel.shapes[i].t != "") { // Modify field value checkBoxField.Checked = Convert.ToBoolean(uploadPicModel.shapes[i].t); } } else if (uploadPicModel.shapes[i].fieldType == "Radio") { RadioButtonOptionField field = (RadioButtonOptionField)doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)]; RadioButtonField rbf = (RadioButtonField)field.Parent; if (Convert.ToBoolean(uploadPicModel.shapes[i].t)) { rbf.Selected = rbf.Options[field.OptionName].Index; } else { field.ActiveState = "Off"; } } else if (uploadPicModel.shapes[i].fieldType == "ComboBox") { // Get a field ComboBoxField comboBoxField = doc.Form.Fields[Convert.ToInt32(uploadPicModel.shapes[i].imName)] as ComboBoxField; var values = uploadPicModel.shapes[i].t.Split(new[] { "^^^" }, StringSplitOptions.None)[0]; foreach (var item in comboBoxField.Options.Cast <Option>()) { if (item.Value == values) { comboBoxField.Selected = item.Index; } } } } } doc.Save(Config.Configuration.OutputDirectory + "/Export.pdf"); return(Ok(new DocStatusModel())); }
private void AddHeaderFooter(Document doc, string headerText, string footerText) { try { // Adding header and footer of the page... TextStamp headerTextStamp = new TextStamp(headerText); //set properties of the stamp headerTextStamp.TopMargin = 10; //textStamp.LeftMargin = 400; headerTextStamp.HorizontalAlignment = HorizontalAlignment.Center; headerTextStamp.VerticalAlignment = VerticalAlignment.Top; //add header on all pages foreach (Aspose.Pdf.Page pg in doc.Pages) { pg.AddStamp(headerTextStamp); } //add foter on all pages (same as header)... foreach (Aspose.Pdf.Page pg in doc.Pages) { TextStamp footerTextStamp = new TextStamp("Page No: " + pg.Number); footerTextStamp.BottomMargin = 10; footerTextStamp.HorizontalAlignment = HorizontalAlignment.Center; footerTextStamp.VerticalAlignment = VerticalAlignment.Bottom; pg.AddStamp(footerTextStamp); } } catch (Exception exp) { msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Exception Occured:" + exp.Message + "</div>"; } }
//method for pagewatermarkings and stamping private static void WaterMarkDocument(string pdfDocumentPath, string hflDocumentPath, string stampText, List<string> watermarkingValues) { try { Aspose.Pdf.Document document = new Aspose.Pdf.Document(pdfDocumentPath); Aspose.Pdf.Document hfl = new Aspose.Pdf.Document(hflDocumentPath); //create page stamp PdfPageStamp pageStamp = null; foreach (var value in watermarkingValues) { string[] waterMark = value.Split('='); string hflDocPageNo = waterMark[waterMark.Length - 1]; string docPageNo = waterMark[waterMark.Length - 2]; //Console.WriteLine(hflDocPageNo + " " + docPageNo); //Console.ReadKey(); int hflDocPageNumber = Convert.ToInt32(hflDocPageNo); if (docPageNo == "[ALL]") { //create page stamp pageStamp = new PdfPageStamp(hfl.Pages[hflDocPageNumber]); //add stamp to all pages for (int pageCount = 1; pageCount <= document.Pages.Count; pageCount++) { //add stamp to particular page document.Pages[pageCount].AddStamp(pageStamp); } } else { int docPageNumber = Convert.ToInt32(docPageNo); //create page stamp pageStamp = new PdfPageStamp(hfl.Pages[hflDocPageNumber]); if (docPageNumber <= document.Pages.Count) { //add stamp to particular page document.Pages[docPageNumber].AddStamp(pageStamp); } } } if (stampText.Length > 0) { //Create text stamp TextStamp textStamp = new TextStamp(stampText); //set whether stamp is background textStamp.Background = true; //set origin textStamp.XIndent = 420; textStamp.YIndent = 825; textStamp.TextState.FontSize = 8.0F; pageStamp.Background = true; //add stamp to particular page document.Pages[1].AddStamp(textStamp); } //finally save the pdf document document.Save(pdfDocumentPath); writeToLog("Final document " + document.FileName.ToString() + " Produced"); } catch (Exception e) { Console.WriteLine("Application PDBOT failed with error: " + e.Message + "." + e.StackTrace); writeToLog("Error saving final document " + e.StackTrace); Console.ReadKey(); } }
/// <summary> /// 以角度線性期function來呈現 /// </summary> /// <param name="pdfPage"></param> /// <param name="arg"></param> private static void AddWatermarkRepeatRotateAngle(Aspose.Pdf.Page pdfPage, WatermarkArg arg) { if (arg.WatermarkHeight < minValue) { throw new ArgumentException($"{nameof(arg.WatermarkHeight)} must greater than {minValue}"); } if (arg.WatermarkWidth < minValue) { throw new ArgumentException($"{nameof(arg.WatermarkWidth)} must greater than {minValue}"); } var text = new FormattedText(arg.Watermark); var yIndent = pdfPage.CropBox.Height - arg.WatermarkHeight; var yLimit = 0 - (arg.WatermarkHeight + arg.WatermarkVerticalSpace); var pageWidth = pdfPage.CropBox.Width; var pageHeight = pdfPage.CropBox.Height; var xIndent = 0d; while (yIndent > yLimit) { var y = yIndent; while (xIndent < pageWidth && y < pageHeight) { var stamp = new TextStamp(text); stamp.RotateAngle = arg.RotateAngle; stamp.XIndent = xIndent; stamp.YIndent = y; stamp.Opacity = arg.Opacity; stamp.Width = arg.WatermarkWidth; stamp.Height = arg.WatermarkHeight; pdfPage.AddStamp(stamp); xIndent += (arg.WatermarkWidth + arg.WatermarkHorizontalSpace); xIndent = xIndent + Math.Cos(30) * arg.WatermarkWidth; y = y + Math.Sign(30) * (arg.WatermarkHeight + arg.WatermarkVerticalSpace); } xIndent = 0; var yIdentReduce = (arg.WatermarkHeight + arg.WatermarkVerticalSpace); yIndent -= yIdentReduce; } //到底了,要再連走 X var baseX = 0d; while (baseX < pageWidth) { var y = yIndent; xIndent = baseX; while (xIndent < pageWidth) { var stamp = new TextStamp(text); stamp.RotateAngle = arg.RotateAngle; stamp.XIndent = xIndent; stamp.YIndent = y; stamp.Opacity = arg.Opacity; stamp.Width = arg.WatermarkWidth; stamp.Height = arg.WatermarkHeight; pdfPage.AddStamp(stamp); xIndent += (arg.WatermarkWidth + arg.WatermarkHorizontalSpace); xIndent = xIndent + Math.Cos(30) * arg.WatermarkWidth; y = y + Math.Sign(30) * (arg.WatermarkHeight + arg.WatermarkVerticalSpace); } baseX += (arg.WatermarkWidth + arg.WatermarkHorizontalSpace);; } }
private MemoryStream AddFooterToFile(Document pdfDocument, ref PdfFileStamp pdfStamp, string sUserName, DateTime dtCurrentDate, string sCompany) { //create footer List <TextStamp> ltFooterStamp = new List <TextStamp>(); TextStamp footerStamp = null; //footerStamp = new TextStamp("Document ID: "); ////set properties of the stamp //footerStamp.BottomMargin = 10; //footerStamp.XIndent = 20; ////footerStamp.HorizontalAlignment = HorizontalAlignment.Left; //footerStamp.VerticalAlignment = VerticalAlignment.Bottom; //footerStamp.TextState.FontStyle = FontStyles.Bold; //ltFooterStamp.Add(footerStamp); //footerStamp = new TextStamp(documentGuid.ToString()); ////set properties of the stamp //footerStamp.BottomMargin = 10; //footerStamp.XIndent = 130; ////footerStamp.HorizontalAlignment = HorizontalAlignment.Left; //footerStamp.VerticalAlignment = VerticalAlignment.Bottom; //footerStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); //ltFooterStamp.Add(footerStamp); string sTextDate = dtCurrentDate.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); FormattedText wtext = new FormattedText("Confidential", new FontColor(220, 20, 60), new FontColor(255, 255, 255), Aspose.Pdf.Facades.FontStyle.HelveticaBold, EncodingType.Winansi, true, 17); wtext.AddNewLineText(sUserName, 5); wtext.AddNewLineText(sTextDate, 5); footerStamp = new TextStamp(wtext); ltFooterStamp.Add(footerStamp); float fWidth = wtext.TextWidth; Dictionary <Tuple <double, double>, List <int> > dictMeasurements = new Dictionary <Tuple <double, double>, List <int> >(); int nPageCount = 1; foreach (Aspose.Pdf.Page pg in pdfDocument.Pages) { foreach (TextStamp ts in ltFooterStamp) { pg.AddStamp(ts); } nPageCount++; } MemoryStream outStream = new MemoryStream(); //save updated PDF file pdfStamp.Save(outStream); return(outStream); }
public static void UploadPic(List<shap> shapes , string filename, string aspectRatio) { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //Create image stamp ImageStamp imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png")); for (int i = 0; i < shapes.Count; i++) { //create stamp Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); float shapeX = (shapes[i].x * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeY = (shapes[i].y * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeW = (shapes[i].w * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); float shapeH = (shapes[i].h * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio); double yaxis = (float)(doc.Pages[shapes[i].p].Rect.URY - (shapeH + shapeY)); var isSpecial = true;//regexItem.IsMatch(shapes[i].imName); if (shapes[i].Itype == "highlight" || shapes[i].Itype == "image") { if (shapes[i].Itype == "highlight") { imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png")); } else { imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("Images/"+shapes[i].imName)); } imageStamp.Background = false; imageStamp.XIndent = (float)(shapeX); imageStamp.YIndent = (float)(yaxis); imageStamp.Height = shapeH; imageStamp.Width = shapeW; //Add stamp to particular page doc.Pages[shapes[i].p].AddStamp(imageStamp); } else if(shapes[i].Itype == "text") { /* // create TextBuilder for first page TextBuilder tb = new TextBuilder(doc.Pages[shapes[i].p]); // TextFragment with sample text TextFragment fragment = new TextFragment(shapes[i].t); // set the font for TextFragment fragment.TextState.Font = FontRepository.FindFont(shapes[i].n); fragment.TextState.FontSize = Convert.ToInt32(shapes[i].s); if (shapes[i].wt == "bold") { fragment.TextState.FontStyle = FontStyles.Bold; } if (shapes[i].st == "italic") { fragment.TextState.FontStyle = FontStyles.Italic; } // set the formatting of text as Underline // fragment.TextState.Underline = true; fragment.TextState.ForegroundColor = GetColor(shapes[i].c); // specify the position where TextFragment needs to be placed fragment.Position = new Position((float)(shapeX), (float)(yaxis)); // fragment.Rectangle.Rotate((360 - (Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI); // append TextFragment to PDF file tb.AppendText(fragment); */ //create text stamp TextStamp textStamp = new TextStamp(shapes[i].t); //set whether stamp is background // textStamp.Background = true; //set origin textStamp.XIndent = (float)(shapeX); textStamp.YIndent = (float)(yaxis); //rotate stamp textStamp.RotateAngle = 360 - ((Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI); //set text properties textStamp.TextState.Font = FontRepository.FindFont(shapes[i].n); textStamp.TextState.FontSize = Convert.ToInt32(shapes[i].s) * 0.75f; if (shapes[i].wt == "bold") { textStamp.TextState.FontStyle = FontStyles.Bold; } if (shapes[i].st == "italic") { textStamp.TextState.FontStyle = FontStyles.Italic; } textStamp.TextState.ForegroundColor = GetColor(shapes[i].c); //add stamp to particular page doc.Pages[shapes[i].p].AddStamp(textStamp); } else if (shapes[i].Itype == "field" && isSpecial) { if (shapes[i].fieldType == "Text") { // Get a field TextBoxField textBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as TextBoxField; // Modify field value textBoxField.Value = shapes[i].t; } else if (shapes[i].fieldType == "CheckBox") { // Get a field CheckboxField checkBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as CheckboxField; if(shapes[i].t != "") // Modify field value checkBoxField.Checked = Convert.ToBoolean(shapes[i].t); } else if (shapes[i].fieldType == "Radio") { RadioButtonOptionField field = (RadioButtonOptionField)doc.Form.Fields[Convert.ToInt32(shapes[i].imName)]; RadioButtonField rbf = (RadioButtonField)field.Parent; if (Convert.ToBoolean(shapes[i].t)) { rbf.Selected = rbf.Options[field.OptionName].Index; } else { field.ActiveState = "Off"; } } else if (shapes[i].fieldType == "ComboBox") { // Get a field ComboBoxField comboBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as ComboBoxField; var values = shapes[i].t.Split(new string[]{"^^^"},StringSplitOptions.None)[0]; foreach (var item in comboBoxField.Options.Cast<Option>()) { if (item.Value == values) { comboBoxField.Selected = item.Index; } } } } } doc.Save(HttpContext.Current.Server.MapPath("Convert/Export.pdf")); }
/// <summary> /// 輸入 DataTable 轉成 有浮水印 的 PDF /// </summary> /// <param name="dt"></param> /// <param name="columnNameMappings"></param> /// <param name="folderName"></param> /// <param name="watermark"></param> /// <param name="pot"></param> /// <returns>產生的 pdf 檔名 (fullpath) </returns> private static string GenPDF(DataTable dt, Dictionary <string, string> columnNameMappings , string folderName, string watermark, PageOrientationType pot) { ChangeColumnDisplayName(dt, columnNameMappings); //output file name var fileNameWithoutExt = $"{Guid.NewGuid().ToString("N")}"; var outputExcel = Path.Combine(folderName, $"{fileNameWithoutExt}_tmp.xlsx"); var tempPdf = Path.Combine(folderName, $"{fileNameWithoutExt}_tmp.pdf"); var outputPdf = Path.Combine(folderName, $"{fileNameWithoutExt}.pdf"); //proc excel // Instantiating a Workbook object var workbook = new Workbook(); var worksheet = workbook.Worksheets[0]; worksheet.Cells.ImportDataTable(dt, true, "A1"); worksheet.AutoFitColumns(); worksheet.AutoFitRows(); var range = worksheet.Cells.MaxDisplayRange; var pageSetup = workbook.Worksheets[0].PageSetup; //var titleEndColumnName = CellsHelper.ColumnIndexToName(range.ColumnCount-1); //pageSetup.PrintTitleColumns = $"$A:${titleEndColumnName}"; pageSetup.PrintTitleRows = "$1:$1"; pageSetup.IsPercentScale = true; pageSetup.Orientation = pot; //border //Setting border for each cell in the range var style = workbook.CreateStyle(); var colorBlack = System.Drawing.Color.Black; style.SetBorder(BorderType.BottomBorder, CellBorderType.Medium, colorBlack); style.SetBorder(BorderType.LeftBorder, CellBorderType.Medium, colorBlack); style.SetBorder(BorderType.RightBorder, CellBorderType.Medium, colorBlack); style.SetBorder(BorderType.TopBorder, CellBorderType.Medium, colorBlack); range.SetStyle(style); // Saving the Excel file //workbook.Save(outputExcel); //workbook.Save(tempPdf); //save to stream var pdfStream = new MemoryStream(); workbook.Save(pdfStream, Aspose.Cells.SaveFormat.Pdf); var pdfDocument = new Aspose.Pdf.Document(pdfStream); if (!string.IsNullOrWhiteSpace(watermark)) { //針對 PDF 加入 Watermark Aspose.Pdf.Facades.Stamp aStamp = new Aspose.Pdf.Facades.Stamp(); aStamp.Rotation = 45; var textStamp = new TextStamp(watermark); //set properties of the stamp // textStamp.Background = true; textStamp.Opacity = 0.2; textStamp.TextState.FontSize = 60.0F; textStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.VerticalAlignment = VerticalAlignment.Center; textStamp.RotateAngle = aStamp.Rotation; textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.Gray; foreach (var page in pdfDocument.Pages) { page.AddStamp(textStamp); } } pdfDocument.Save(outputPdf); return(outputPdf); }
public static void UsingTextStamp() { // ExStart:UsingTextStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create Document instance Document pdfDocument = new Document(); // Add page to pages collection of Document Page page = pdfDocument.Pages.Add(); // Instantiate TextStamp instance with sample text TextStamp stamp = new TextStamp("This is text stamp with character spacing"); // Specify font name for Stamp object stamp.TextState.Font = FontRepository.FindFont("Arial"); // Specify Font size for TextStamp stamp.TextState.FontSize = 12; // Specify character specing as 1f stamp.TextState.CharacterSpacing = 1f; // Set the XIndent for Stamp stamp.XIndent = 100; // Set the YIndent for Stamp stamp.YIndent = 500; // Add textual stamp to page instance stamp.Put(page); dataDir = dataDir + "CharacterSpacingUsingTextStamp_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:UsingTextStamp Console.WriteLine("\nCharacter spacing specified successfully using text stamp.\nFile saved at " + dataDir); }