WPF Printdocument - wpf

Got this code below, how can I send an excel file to the printer?
Edit: I want to send an existing file (excel) to my "Microsoft Print to PDF" printer and then have it save it as a new file (pdf).
PrintDocument doc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",
PrintToFile = true,
PrintFileName = System.IO.Path.Combine(#AppDomain.CurrentDomain.BaseDirectory + "\\pdf\\", "filename.pdf"),
}
};
doc.Print();

Related

Why is my PrintDialog always opening "save as" and not print directly?

So I have an Window which I want to Print. For that I created an Print Dialog. Which looks like that:
PrinterSettings settings = new PrinterSettings();
string Printer = settings.PrinterName;
System.Windows.Controls.PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
printDlg.PrintQueue = new PrintQueue(new PrintServer(), Printer);
printDlg.PrintTicket.CopyCount = 1;
printDlg.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDlg.PrintVisual(this, "Window Printing.");
But for some reason it opens instant an Dialog for save that Programm as PDF. But I want directly print it to my Printer, without that Dialog. So why does it not Print to my Printer? And how Can I get this to work.
Are you sure you have chosen the correct printer? Because the PrintDialog will behave like this if its printer is set to a file printer, for example to: "Microsoft Print to PDF". (Then, obviously, you have to provide the name of the file the printer should print to, hence the "save" dialog.)
Check what printers you have installed (or rather, what PrintQueues you have available):
LocalPrintServer myPrintServer = new LocalPrintServer();
foreach (PrintQueue pq in myPrintServer.GetPrintQueues())
{
Console.WriteLine(pq.Name);
}
Are you sure you're setting one of those? Which one is the default in your system? Is it maybe a file printer?
Try setting a printer name to the correct, physical printer in code, and check if anything will print:
string myPrinterName = "My Printer"; // <= put an existing name here
LocalPrintServer myPrintServer = new LocalPrintServer();
PrintDialog printDlg = new PrintDialog();
PrintQueue printQueue = myPrintServer.GetPrintQueue(myPrinterName);
printDlg.PrintQueue = printQueue;
printDlg.PrintTicket.CopyCount = 1;
printDlg.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDlg.PrintVisual(this, "Window Printing.");
In the system, is the printer configured correctly?

Programmatically add Checkbox Content Controls to Word document using OpenXML

Is there an easy/straightforward way to dynamically add (not edit the value of) multiple checkbox controls in a .docx document body?
I tried appending a single SdtContentCheckBox after a new paragraph like this but with no luck:
newParagraph.Append(new SdtContentCheckBox());
and also followed the instructions here:
https://www.codeproject.com/Tips/370758/Add-dynamic-content-controls-to-a-word-document and here: How do I create a check box in C# using Open XML SDK
The first one showed only how to add a text content control and the second one straight up resulted in a corrupted .docx file.
Any help would be appreciated!
Closest working code I could find was this:
https://social.msdn.microsoft.com/Forums/office/en-US/f6ce8ecf-0ed8-4f18-958a-a086f212d1e2/how-to-create-a-checked-checkbox-form-field-using-the-sdk?forum=oxmlsdk
public static Paragraph GenerateParagraph()
{
var element =
new Paragraph(
new Run(
new FieldChar(
new FormFieldData(
new FormFieldName(){ Val = "Check1" },
new Enabled(),
new CalculateOnExit(){ Val = BooleanValues.Zero },
new CheckBox(
new AutomaticallySizeFormField(),
new DefaultCheckboxFormFieldState(){ Val = BooleanValues.Zero }))
){ FieldCharType = FieldCharValues.Begin }),
new BookmarkStart(){ Name = "Check1", Id = 0 },
new Run(
new FieldCode(" FORMCHECKBOX "){ Space = "preserve" }),
new Run(
new FieldChar(){ FieldCharType = FieldCharValues.End }),
new BookmarkEnd(){ Id = 0 },
new Run(
new Text("My check box"))
){ RsidParagraphAddition = "00784880", RsidRunAdditionDefault = "00B77989" };
return element;
}
Using this I was able to dynamically add Legacy Checkboxes (i.e. neither Content control nor ActiveX control), but at least it is a start!
If someone knows how to add Checkbox Content controls, feel free to post a reply below and I'll mark it as Correct.
Even though you found yourself the answer, I'll leave this here in case anyone stumbles upon this looking for something related.
There's a tool called Open XML SDK 2.5 Productivity Tool, which you can download from here that allows you to reverse-engineer a word .docx document to obtain the C# code to generate it from scratch.
In order to get the code that you are looking for to generate any kind of word element (a checkbox, a table, a bulleted list...), you need to create a word document with said element and save it.
Then, open it using the Open XML SDK 2.5 Productivity Tool and click on the "Reflect Code" button. The generated code will show you how to create those elements, styles and other formatting included.
With that, I got the code necessary to get a paragraph with a checkbox
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
public static Paragraph GenerateCheckboxParagraph(string internalName, int internalId, string textAfterTextbox)
{
var run1 = new Run(
new FieldChar(
new FormFieldData(
new FormFieldName() { Val = internalName },
new Enabled(),
new CalculateOnExit() { Val = OnOffValue.FromBoolean(false) },
new CheckBox(
new AutomaticallySizeFormField(),
new DefaultCheckBoxFormFieldState() { Val = OnOffValue.FromBoolean(false) }))
)
{
FieldCharType = FieldCharValues.Begin
}
);
var run2 = new Run(new FieldCode(" FORMCHECKBOX ") { Space = SpaceProcessingModeValues.Preserve });
var run3 = new Run(new FieldChar() { FieldCharType = FieldCharValues.End });
var run4 = new Run(new Text(textAfterTextbox));
var element =
new Paragraph(
run1,
new BookmarkStart() { Name = internalName, Id = new StringValue(internalId.ToString()) },
run2,
run3,
new BookmarkEnd() { Id = new StringValue(internalId.ToString()) },
run4
);
return element;
}

Save file to Document directory in liferay 6.1 using API

I need to save a uploaded file in sub directory of Document & Media folder in liferay from web-form portlet.
I have extended the web Form portlet to do so, but file is getting uploaded successfully in database & not in Document & Media folder.
I tried following code to upload the file in document directory but no success please help .
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
String title = file.getName();
DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), 0, "Test");
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(),actionRequest);
Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
long fileEntryTypeId = DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT;
FileInputStream inputStream = new FileInputStream(file);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(), 10153, dlFolder.getRepositoryId(),
dlFolder.getRepositoryId(), title, file.getContentType(), title, "fileDesc", "sss",
fileEntryTypeId, fieldsMap, file, inputStream, file.length(), serviceContext);
inputStream.close();
DLFileEntryLocalServiceUtil.updateFileEntry(themeDisplay.getUserId(), dlFileEntry.getFileEntryId(), title, file.getContentType(),
title, "fileDesc", "comment", true, dlFileEntry.getFileEntryTypeId(), fieldsMap, file, null, file.length(), serviceContext);
Try this code snippet
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
File file = uploadRequest.getFile("file");
String contentType = MimeTypesUtil.getContentType(file);
InputStream inputStream = new FileInputStream(file);
Folder folderName = DLAppLocalServiceUtil.getFolder(parentRepositoryId,
parentFolderId,
"Folder Name");
long folderId = folderName.getFolderId();
long repositoryId = folderName.getRepositoryId();
FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
repositoryId,
folderId,
file.getName(),
contentType,
"File Name",
"description",
"changeLog",
inputStream,
file.length(),
serviceContext);
I know it's an old question, but I had similar issue today. I used DLFileEntryLocalServiceUtil, and I had to call both addFileEntry() and updateFileEntry() in order to correctly create the asset.
See Liferay DLFileEntryLocalServiceUtil.addFileEntry does not create AssetEntry record

Import data from Excel file in Silverlight application

I am using VS2010, Silverlight 5.0
I am trying to Import Data from Excel file to Grid, for that I am using an 'OpenFileDialog'. User can Input Excel file using OpenFileDialog like this
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*";
bool bResult = (bool)dlg.ShowDialog();
if (!bResult)
return "";
FileInfo info = dlg.File;
StatusText.Text = info.Name;
Stream s = info.OpenRead();
StreamReader reader = new StreamReader(s);
string xml = reader.ReadToEnd();
var doc = XDocument.Parse(xml);
In Case of Microsoft Excel Format 2003 or 2007(.xls file) above code works fine and gives me values from Excel in a string.
But in case of Microsoft Excel Format 2010(.xlsx file) the reader.ReadToEnd() does not return values in proper format so the next line, give me following Error.
var doc = XDocument.Parse(xml);
'Data at the root level is invalid. Line 1, position 1'
How can I solve this error, or what is the best way to import data from excel?

How to deliver bitmap to the server?

Writing my first silverlight application.
I need to deliver some bitmap that the customer will choose ( used OpenFileDialog ) to the server side ( using web service ).
After the customer choosing the bitmap - i cant access the file and break hit to byte array because i dont see the file full path on the OpenFileDialog object properties.
How can i do it ?
( i have method that get Bitmap and return the bitmap as byte array )
I did that before, here is part of it:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Images (*.png; *.jpg)| *.png; *.jpg";
dialog.Multiselect = false;
if (dialog.ShowDialog() == true)
{
using (System.IO.Stream stream = dialog.File.OpenRead())
{
BinaryReader binaryReader = new BinaryReader(stream);
// here are the bytes you want, put them somewhere to send them to the server
byte[] imageBytes = binaryReader.ReadBytes((int)stream.Length);
// here is the filename if you need it
string filename = System.IO.Path.GetFileNameWithoutExtension(dialog.File.Name);
stream.Close();
}
}

Resources