I'm trying to attach a PDF File to a Print Dialog, but I haven't find out the way to do it.
I'm using a WPF app, and I have some code related with printing and looks like this:
private void Imprimir()
{
try
{
FixedDocument document = null;
PageContent pageContent = null;
FixedPage fixedPage = null;
PrintDialog printDlg = new PrintDialog();
if (printDlg.ShowDialog() != true)
return;
document.DocumentPaginator.PageSize = new System.Windows.Size(1400, 1450);
fixedPage.Width = document.DocumentPaginator.PageSize.Width;
fixedPage.Height = document.DocumentPaginator.PageSize.Height;
fixedPage.Margin = new Thickness(96, 96, 0, 0);
fixedPage.Children.Add(this);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
document.Pages.Add(pageContent);
printDlg.PrintDocument(document.DocumentPaginator, "Impresion Cierre");
fixedPage.Children.Clear();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
But, by this way I'm just printing a UI Element added to Fixed Page.
I've looked for other codes, but I find nothing.
So, I donĀ“t know if is possible to add a PDF File stored locally to the Print Dialog ?
Thanks for the help...
Well you cannot do this using PrintDialog. There are several options, depending on your goals:
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var input = File.OpenRead("path_to_your.pdf")) {
using (var job = printQueue.AddJob()) {
using (var output = job.JobStream) {
input.CopyTo(output);
}
}
}
Will silently send print job for your file to local print queue. Print job is configurable.
Alternatively you can use adobe reader to handle that for you (or another pdf reader installed on user's machine) but starting process with path to your pdf as FileName and Verb="print".
One more option is to use third party tools (like ghostscript) which can help you with that.
Related
I want to write my own PrintPreview for larger text using a DocumentViewer to display it later.
I have not found anything usefully for my problem.
At the moment I'm searching for a way to get the content of the individual pages.
I found a way to access the individual pages, but I can't store or get it.
Using the code:
DocumentPaginator dpPages = (DocumentPaginator)((IDocumentPaginatorSource)twhtTemp.BuildTemplateControl(txtHeader, txtContent, pdlgPrint)).DocumentPaginator;
dpPages.ComputePageCount();
var fixedDocument = new FixedDocument();
for (int iPages= 0; iPages < dpPages.PageCount; iPages++)
{
var pageContent = new PageContent();
var fixedPage = new FixedPage();
fixedPage.Width = pdlgPrint.PrintableAreaWidth;
fixedPage.Height = pdlgPrint.PrintableAreaHeight;
pageContent.Child = fixedPage;
fixedDocument.Pages.Add(pageContent);
}
I'm already adding a new page for each existing page, but I can't get the content of the page.
So far I know, I need a UIElement to add to fixedPage.Children.
Or is there some easier way to get a flowdocument to a fixed document with many fixedpages (deppending to the pages count)?
i hate it to answer my own questions.
After searching three days i asked here.
One day later i found a way...
It's been a long time since the question has been answered.
I tried Doo Dah's answer, but the problem was that it doesn't take care of the page paddings of a flowdocument.
Therefore I wrote my own solution (Doo Dah's answer helped me to complete it):
public FixedDocument Get_Fixed_From_FlowDoc(FlowDocument flowDoc, PrintDialog printDlg)
{
var fixedDocument = new FixedDocument();
try
{
if (printDlg != null)
{
pdlgPrint = printDlg;
}
if (pdlgPrint == null)
{
pdlgPrint = new PrintDialog();
}
DocumentPaginator dpPages = (DocumentPaginator)((IDocumentPaginatorSource)flowDoc).DocumentPaginator;
dpPages.ComputePageCount();
PrintCapabilities capabilities = pdlgPrint.PrintQueue.GetPrintCapabilities(pdlgPrint.PrintTicket);
for (int iPages= 0; iPages < dpPages.PageCount; iPages++)
{
var page = dpPages.GetPage(iPages);
var pageContent = new PageContent();
var fixedPage = new FixedPage();
Canvas canvas = new Canvas();
VisualBrush vb = new VisualBrush(page.Visual);
vb.Stretch = Stretch.None;
vb.AlignmentX = AlignmentX.Left;
vb.AlignmentY = AlignmentY.Top;
vb.ViewboxUnits = BrushMappingMode.Absolute;
vb.TileMode = TileMode.None;
vb.Viewbox = new Rect(0, 0, capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
FixedPage.SetLeft(canvas, 0);
FixedPage.SetTop(canvas, 0);
canvas.Width = capabilities.PageImageableArea.ExtentWidth;
canvas.Height = capabilities.PageImageableArea.ExtentHeight;
canvas.Background = vb;
fixedPage.Children.Add(canvas);
fixedPage.Width = pdlgPrint.PrintableAreaWidth;
fixedPage.Height = pdlgPrint.PrintableAreaHeight;
pageContent.Child = fixedPage;
fixedDocument.Pages.Add(pageContent);
}
dv1.ShowPageBorders = true;
}
catch (Exception)
{
throw;
}
return fixedDocument;
}
You had to build a FlowDocument of the content you will show before and pass it
to the Method.
Added the PrintDialog variable to call the Method from my preview window and can pass the current printer settings.
If you call it from your main programm, you either can pass a new PrintDialog() or null, there is no difference, because it will create a new PrintDialog if you are passing null
This worked fine for me with a Flowdocument with different types of text (header, text, font).
It should work with pictures and text mixed, or only pictures, too - it's using the visuals and not something specific from a flowdocument, therefore it should work with pagebreaks, too.
I don't tryed Shahin Dohan'S answer, because it's the same problem as so often.
It's written at MVVM and very hard to understand when another person has written it.
At my opinion it would be better to write a little example programm without mvvm and the people can adept it to mvvm or use only the code.
I understand the opportunities of mvvm, but to show someone how to works something i see only disadvantages (if you will not show a specific mvvm mechanic)
Is it possible in WPF to get content of each DocumentPage by page number?
You can follow this then add each extracted TextRange to whatever you want.
I am new to react-native and I seek your help please. What I am planning to do is to get the app icon associated with an app that the user has installed on his device.
I did take a look at this code and realized that I have no way of passing it back to my JS.
Here is what I am doing currently.
private List<String> getNonSystemApps() {
List<PackageInfo> packages = this.reactContext
.getPackageManager()
.getInstalledPackages(0);
List<String> ret = new ArrayList<>();
for (final PackageInfo p: packages) {
if ((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", p.packageName);
jsonObject.put("firstInstallTime", p.firstInstallTime);
jsonObject.put("installLocation", p.installLocation);
jsonObject.put("applicationInfo", p.applicationInfo);
jsonObject.put("permissions", getPermissionsByPackageName(p.packageName));
Drawable icon = reactContext.getPackageManager().getApplicationIcon(p.packageName);
ret.add(jsonObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ret;
}
Can you please help me out with this ?
Thanks
Edit
I managed to get it working, based on Aaron's suggestion, I created another private function just to work with the images. This function will generate the base 64 version of an app's icon.
private String getBitmapOfAnAppAsBase64(String packageName) {
if(packageName.isEmpty() ) return new String("");
String base64Encoded = "";
Bitmap bitmap;
try {
Drawable appIcon = this.reactContext.getPackageManager().getApplicationIcon(packageName);
if(appIcon instanceof BitmapDrawable) {
bitmap= ((BitmapDrawable)appIcon).getBitmap();
} else {
bitmap = Bitmap.createBitmap(appIcon.getIntrinsicWidth(), appIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
base64Encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch(Exception e) {
Log.d(TAG,"An error was encounted while getting the package information. The error follows : " + e.toString());
}
return base64Encoded;
}
I then use this generated string in my original function, with the following modifications.
Old Non working code
Drawable icon = reactContext.getPackageManager().getApplicationIcon(p.packageName);
New working code
jsonObject.put("icon", getBitmapOfAnAppAsBase64(p.packageName));
and then in React-Native - its a piece of pie, since it supports base64 already.
"icon" : 'data:image/png;base64,'+installAppObj.icon
Huge thanks to Aaron , for guiding me in the correct direction.
If you haven't already, read through the entire Android Native Modules page. It's not that long and addresses several issues you're likely to run into.
Only these types can be sent to your JS code (via a #ReactMethod):
Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array
So you effectively have two options:
Encode the Drawable to one of these types, then decode it on the JavaScript side, or
Write the file to disk, and send the path over
I'm not sure what type of Drawable the icon is or if there are guarantees. But any of them should be convertible in some way. For example if it's a Bitmap you can do a Bitmap to Base64 String conversion.
I am doing html to pdf file . Its Downloading instantly . I dont want download instantly. i want to save the file in my project folder once converted.
My C# Code
string html ="<table><tr><td>some contents</td></tr></table>";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
StringReader sr = new StringReader(table);
Document ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30);
PdfPTable Headtable = new PdfPTable(7);
Headtable.TotalWidth = 525f;
Headtable.LockedWidth = true;
Headtable.HeaderRows = 5;
Headtable.FooterRows = 2;
Headtable.KeepTogether = true;
HTMLWorker htmlparser = new HTMLWorker(ResultPDF);
PdfWriter.GetInstance(ResultPDF, Response.OutputStream);
ResultPDF.Open();
htmlparser.Parse(sr);
ResultPDF.Close();
Response.Write(ResultPDF);
Response.End();
For saving pdf file locally in your project folder you can use FileStream class like this.
FileStream stream = new FileStream(filePath, FileMode.Create);//Here filePath is path of your project folder.
Now use this stream instead of using Response.OutputStream when you create instance of PdfWriter object.
PdfWriter.GetInstance(ResultPDF, stream);
Now do not use Responce.Write as you don't want to download your file.And close your stream at end.
stream.Close();
I'm going to combine everyone's answer into one that you should be able to drop in and use. If this works, I would accept Manish Parakhiya's answer because that had the most important part.
First, I'm going to assume you are using a recent version of iTextSharp. I think 5.5.5 is the most recent version. Second, because of this, I'm going to restructure your code a bit in order to use the using pattern. If you're stuck on an older obsolete unsupported version like 4.1.6 you'll need to re-adjust.
Almost every tutorial out there shows you that you can bind directly the Response.OutputStream. This is 100% valid but I would argue that it is also a really bad idea. Instead, bind to a more generic MemoryStream. This makes debugging much easier and your code will port and adapt that much easier.
The below code includes comments about each of the changes and what things are actually doing. The top section is all about creating a PDF from a string of HTML. The bottom actually does something with it, including writing it to disk and/or streaming it to a browser.
//Will hold our PDF eventually
Byte[] bytes;
//HTML that we want to parse
string html = "<table><tr><td>some contents</td></tr></table>";
//Create a MemoryStream to write our PDF to
using (var ms = new MemoryStream()) {
//Create our document abstraction
using (var ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30)) {
//Bind a writer to our Document abstraction and our stream
using (var writer = PdfWriter.GetInstance(ResultPDF, ms)) {
//Open the PDF for writing
ResultPDF.Open();
//Parse our HTML using the old, obsolete, not support parser
using (var sw = new StringWriter()) {
using (var hw = new HtmlTextWriter(sw)) {
using (var sr = new StringReader(html)) {
using (var htmlparser = new HTMLWorker(ResultPDF)) {
htmlparser.Parse(sr);
}
}
}
}
//Close the PDF
ResultPDF.Close();
}
}
//Grab the raw bytes of the PDF
bytes = ms.ToArray();
}
//At this point, the bytes variable holds a valid PDF file.
//You can write it disk:
System.IO.File.WriteAllBytes("your file path here", bytes);
//You can also send it to a browser:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.BinaryWrite(bytes);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Never do the next line, it doesn't do what you think it does and actually produces corrupt PDFs
//Response.Write(ResultPDF); //BAD!!!!!!
Response.End();
string tempDirectory = Session.SessionID.ToString();
string location = Path.Combine(Server.MapPath(
WebConfigurationManager.AppSettings["PathSet"].ToString()), tempDirectory);
if (!Directory.Exists(location))
{
Directory.CreateDirectory(location);
}
string fileName="abc.pdf";
filePath = Path.Combine(location, fileName);
As the title sugests, I have a list of SPFiles (sharepoint attachments) and I need to compress it and push to user download it.
I`ve looked for some examples here and tryed to code something but yet no success.
Here follow my last try until now
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
//string nomeEntrada = item.Substring(item.LastIndexOf("/") + 1);
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
//For testing only, to check if the .zip is beeing correctly generated
using (FileStream file = new FileStream("C:\\teste\\file.zip", FileMode.Create, System.IO.FileAccess.Write))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(file);
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=anexos.zip");
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.End();
}
PS: I do not want to save the file in server directory, that was just a test to check if the file was OK
I created an Application Page and redirected user to it. Since I can control the httpcontext by there, I coded the following and it worked just fine. The page quickly stream the file to client and them close itself. Hope it helps
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
stream.Seek(0, SeekOrigin.Begin);
Byte[] byteArray = stream.ToArray();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.AddHeader("Expires", "0");
HttpContext.Current.Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
HttpContext.Current.Response.AddHeader("Content-Description", "Report Export");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"Anexos.zip\"");
HttpContext.Current.Response.BinaryWrite(byteArray);
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}
hi im working on a project that uses invoke and threads.. it is a simple remote desktop program with chat.. i got a sample here on the internet in c# winform, but i would like to convert it to wpf.. i have no problem in sending message to another client using the wpf program but it cannot receive ( or cannot read) the sent messages from the others.. i think it has something to do with the thread and the invoke method, i read that wpf does invoke differently and i did try the dispatcher.invoke, but it still doesnt do the trick
pls hellp
here's the code
wait = new Thread(new ThreadStart(waitForData));
wait.Start();
that snippet above is executed when a successful connection is made in tcpclient
private void waitForData()
{
try
{
NetworkStream read = tcpclnt.GetStream();
while (read.CanRead)
{
byte[] buffer = new byte[64];
read.Read(buffer, 0, buffer.Length);
s = new ASCIIEncoding().GetString(buffer);
System.Console.WriteLine("Recieved data:" + new ASCIIEncoding().GetString(buffer));
rcvMsg = new ASCIIEncoding().GetString(buffer) + "\n";
hasNewData = true;
bool f = false;
f = rcvMsg.Contains("##");
bool comand = false;
comand = rcvMsg.Contains("*+*-");
/*File receive*/
if (f)
{
string d = "##";
rcvMsg = rcvMsg.TrimStart(d.ToCharArray());
int lastLt = rcvMsg.LastIndexOf("|");
rcvMsg = rcvMsg.Substring(0, lastLt);
NetworkStream ns = tcpclnt.GetStream();
if (ns.CanWrite)
{
string dataS = "^^Y";
byte[] bf = new ASCIIEncoding().GetBytes(dataS);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
try
{
new Recieve_File().recieve_file(rcvMsg);
}
catch (Exception ec)
{
System.Console.WriteLine(ec.Message);
}
}
/*Command-shutdown/restart/logoff*/
else if (comand)
{
string com = "*+*-";
rcvMsg = rcvMsg.TrimStart(com.ToCharArray());
execute_command(rcvMsg);
}
else
{
this.Invoke(new setOutput(setOut));
Thread.Sleep(1000);
}
}
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
}
the snippet above is a code that listens if there is a message or command.. the line
this.invoke(new setoutput(setout)) is a code for appending text in the rtb
hope someone could help me thanks
You've posted a lot of code, but I'm assuming it's only the call to Control.Invoke which is causing the problem. In WPF, use Dispatcher.Invoke (or Dispatcher.BeginInvoke) instead, via the Dispatcher property on the relevant UI element.
I'd also strongly encourage you to:
Refactor your code into smaller methods
Stop catching just Exception except at the top level of any large operation (it should just be a fall-back; usually you catch specific exceptions)
Start following .NET naming conventions
Add a using directive for System so you can just write Console.WriteLine instead of System.Console.WriteLine everywhere
Use Encoding.ASCII instead of creating a new ASCIIEncoding each time you need one
Use a StreamReader to read character data from a stream, instead of reading it as binary data first and then encoding it
For either Stream or TextReader, don't ignore the return value from Read - it tells you how many bytes or characters have been read