Skip to content

Instantly share code, notes, and snippets.

@Maxhodges
Created April 6, 2017 12:05
Show Gist options
  • Save Maxhodges/7e6c5ab0145f2b84babc5fc418855f75 to your computer and use it in GitHub Desktop.
Save Maxhodges/7e6c5ab0145f2b84babc5fc418855f75 to your computer and use it in GitHub Desktop.
private void ListenerCallback(IAsyncResult result)
{
try
{
var context = listener.EndGetContext(result);
// Thread.Sleep(1000);
Console.WriteLine("{0}: {1}", DateTime.Now, context.Request.Headers);
//functions used to decode json encoded data.
//JavaScriptSerializer js = new JavaScriptSerializer();
//var data1 = Uri.UnescapeDataString(data_text);
//string da = Regex.Unescape(data_text);
// var unserialized = js.Deserialize(data_text, typeof(String));
// var cleaned_data = System.Web.HttpUtility.UrlDecode(data_text);
Console.WriteLine("url={0}", context.Request.Url);
string[] segments = context.Request.Url.Segments;
Console.WriteLine("segment1={0}", segments[1]);
int statusCode = 418;
string statusDescription = "";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, =, X-Requested-With");
switch (segments[1])
{
case "print-pdf":
case "print-pdf/":
{
// get payload
string data_text = new StreamReader(context.Request.InputStream, true).ReadToEnd();
// ignore requests with no payload
if (!string.IsNullOrEmpty(data_text))
{
Console.WriteLine("dat_text not null: {0}", data_text);
// Parse the query string variables into a NameValueCollection.
NameValueCollection qscol = HttpUtility.ParseQueryString(data_text);
string PDFurl = qscol["url"];
string orderId = qscol["fulfillment-order-id"];
logger.Info("print-pdf: " + orderId);
Console.WriteLine("before PDFUtil");
PDFutil.PDFutil pdfPrinter = new PDFutil.PDFutil();
Console.WriteLine("after PDFUtil");
using (var client = new WebClient())
using (Stream mystream = client.OpenRead(PDFurl))
{
using (var memStream = new MemoryStream())
{
// required to make stream support seek operations
mystream.CopyTo(memStream);
Console.WriteLine("before add signatures");
using (var stream2 = pdfPrinter.AddSignatures(memStream))
{
Console.WriteLine("before addmartingtext");
using (var stream3 = pdfPrinter.AddMarginText(stream2, orderId))
{
using (var outputMemstream = new MemoryStream())
{
stream3.CopyTo(outputMemstream);
Console.WriteLine("before pdfPrint");
//pdfPrinter.PrintPDF(outputMemstream, orderid);
pdfPrinter.AcrobatPrintPDF(outputMemstream, orderId);
pdfPrinter = null;
}
}
}
}
}
}
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
break;
}...
REST below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Pdf.Facades;
using System.IO;
using System.Net;
using Aspose.Pdf;
using Aspose.Pdf.Text;
using System.Diagnostics;
using NLog;
namespace PDFutil
{
class PDFutil
{
private static Logger logger = LogManager.GetLogger("PDFutil"); // creates a logger using the class name
public MemoryStream StreamFromURL(string fileURL)
{
using (var client = new WebClient())
using (Stream mystream = client.OpenRead(fileURL))
{
using (var memStream = new MemoryStream())
{
mystream.CopyTo(memStream);
return memStream;
}
}
}
public void PrintPDF(string fileUrl, string MarginText)
{
using (var client = new WebClient())
using (Stream mystream = client.OpenRead(fileUrl))
{
using (var memStream = new MemoryStream())
{
mystream.CopyTo(memStream);
AddMarginText(memStream, MarginText);
}
}
}
private string GetLabelFullFilePath(string labelName)
{
string labelTemplateFileName = "";
labelTemplateFileName = roboAnna.Properties.Settings.Default[labelName].ToString();
string appDir = AppDomain.CurrentDomain.BaseDirectory;
return System.IO.Path.Combine(appDir, labelTemplateFileName);
}
public MemoryStream AddSignatures(Stream pdfStream)
{
//open document
logger.Info("AddSignatures");
var watch = Stopwatch.StartNew();
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfStream);
foreach (Aspose.Pdf.Page page in pdfDocument.Pages)
{
// find sig field on EMS Dispatch Note
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"Signature\sof\sthe\ssender|Date\set\ssignature\sde\sl'expéditeur|\(Signature\)|Date\sand\ssender's\ssignature");
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textFragmentAbsorber.TextSearchOptions = textSearchOptions;
//accept the absorber for teh first page
page.Accept(textFragmentAbsorber);
//get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
//loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
foreach (TextSegment textSegment in textFragment.Segments)
{
// Set coordinates
int lowerLeftX = (int)textSegment.Position.XIndent - 30;
int lowerLeftY = (int)textSegment.Position.YIndent;
int upperRightX = (int)textSegment.Position.XIndent - 30 + 107;
int upperRightY = (int)textSegment.Position.YIndent - 35;
if (textSegment.Text == "(Signature)")
{
lowerLeftX = (int)textSegment.Position.XIndent + 40;
lowerLeftY = (int)textSegment.Position.YIndent + 11;
upperRightX = (int)textSegment.Position.XIndent + 40 + 107;
upperRightY = (int)textSegment.Position.YIndent + 11 - 35;
}
// Get the page where image needs to be added
//Page page = pdfDocument.Pages[1];
// Load image into stream
FileStream imageStream = new FileStream(GetLabelFullFilePath("max_signature"), FileMode.Open);
// Add image to Images collection of Page Resources
page.Resources.Images.Add(imageStream);
// Using GSave operator: this operator saves current graphics state
page.Contents.Add(new Operator.GSave());
// Create Rectangle and Matrix objects
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Aspose.Pdf.Matrix matrix = new Aspose.Pdf.Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new Operator.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
// Using Do operator: this operator draws image
page.Contents.Add(new Operator.Do(ximage.Name));
// Using GRestore operator: this operator restores graphics state
page.Contents.Add(new Operator.GRestore());
// Save updated document
imageStream.Dispose();
}
}
}
MemoryStream outputstream = new MemoryStream();
pdfDocument.Save(outputstream);
pdfDocument.Dispose();
return outputstream;
// pdfDocument.Save(@"c:\temp\output13.pdf");
//watch.Stop();
//Console.WriteLine("elapsed time: {0}", watch.ElapsedMilliseconds);
}
// prints the PDF but can't handle memorystream, so first we need to save it.
public void AcrobatPrintPDF(Stream PDFtoPrint, string orderId)
{
logger.Info("AcrobatPrintPDF " + orderId);
string BASEFILEPATH = roboAnna.Properties.Settings.Default.filePathPDF;
// open memorystream PDF with Aspose.PDF
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(PDFtoPrint);
// save to disk
string filename = orderId + DateTime.Now.ToString("H-mm-ss") + ".pdf";
string fullFilePath = System.IO.Path.Combine(BASEFILEPATH, filename);
logger.Info("Saving " + fullFilePath);
pdfDocument.Save(fullFilePath);
string printerName = roboAnna.Properties.Settings.Default.LaserPrinter;
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "acroRd32.exe";
startInfo.Arguments = @"/t """ + fullFilePath + @""" """ + printerName + @"""";
process.StartInfo = startInfo;
process.Start();
}
public void PrintPDF(Stream PDFtoPrint, string jobName)
{
//Create PdfViewer object
PdfViewer viewer = new PdfViewer();
logger.Info("PrintPDF");
//Open input PDF file
viewer.BindPdf(PDFtoPrint);
// string pdffilename = @"c:\temp\blue.pdf";
// viewer.BindPdf(pdffilename);
//Set attributes for printing
viewer.AutoResize = true; //Print the file with adjusted size
viewer.AutoRotate = true; //Print the file with adjusted rotation
viewer.PrintPageDialog = false; //Do not produce the page number dialog when printing
viewer.PrinterJobName = jobName;
//Create objects for printer and page settings and PrintDocument
System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings();
System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument();
//Set XPS PDF printer name
prtdoc.PrinterSettings.PrinterName = roboAnna.Properties.Settings.Default.LaserPrinter;
ps.PrinterName = prtdoc.PrinterSettings.PrinterName;
//or set the PDF printer
//ps.PrinterName = "Adobe PDF";
//Set PageSize (if required)
pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
//Set PageMargins (if required)
pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);
ps.Duplex = System.Drawing.Printing.Duplex.Simplex;
//Print document using printer and page settings
viewer.PrintDocumentWithSettings(pgs, ps);
// clean up, Close the PDF file after priting
ps = null;
pgs = null;
viewer.Close();
}
public MemoryStream AddMarginText(Stream PDFtoEdit, string MarginText)
{
//Open document
logger.Info("AddMarginText" + MarginText);
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(PDFtoEdit);
//Get particular page
foreach (Aspose.Pdf.Page pdfPage in pdfDocument.Pages)
{
//Create text fragment
TextFragment header = new TextFragment("WRE REF: " + MarginText.ToUpper());
header.Position = new Position(30, 0); //0
//Set text properties
header.TextState.FontSize = 10;
header.TextState.Font = FontRepository.FindFont("Arial");
//Create TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
//Append the text fragment to the PDF page
textBuilder.AppendText(header);
//Create text fragment
TextFragment footer = new TextFragment("WRE REF: " + MarginText.ToUpper());
footer.Position = new Position(30, 825); //0
//Set text properties
footer.TextState.FontSize = 10;
footer.TextState.Font = FontRepository.FindFont("Arial");
//Append the text fragment to the PDF page
textBuilder.AppendText(footer);
}
//Save document
MemoryStream outputStream = new MemoryStream();
pdfDocument.Save(outputStream);
//#if DEBUG
// string filename = MarginText + DateTime.Now.ToString("H-mm-ss") + ".pdf";
// logger.Info("Saving " + filename);
// var watch = Stopwatch.StartNew();
// pdfDocument.Save(@"c:\temp\blue.pdf");
// watch.Stop();
// logger.Info("Saved. elapsed time: "+ watch.ElapsedMilliseconds);
//#endif
//System.Diagnostics.Debugger.Break();
pdfDocument.Dispose();
return outputStream;
//PrintPDF(outputStream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment