Ghostscript.NET.dll print pdf to specified printer - c#

How to print pdf using ghostscript api.
I tried google but still not getting proper solution. Please help me how i do this task.

This should work for you (by using Ghostscript.NET wrapper):
using System;
using System.Collections.Generic;
using Ghostscript.NET.Processor;
namespace Ghostscript.NET.Samples
{
public class SendToPrinterSample : ISample
{
public void Start()
{
// YOU NEED TO HAVE ADMINISTRATOR RIGHTS TO RUN THIS CODE
string printerName = "YourPrinterName";
string inputFile = #"E:\__test_data\test.pdf";
using (GhostscriptProcessor processor = new GhostscriptProcessor())
{
List<string> switches = new List<string>();
switches.Add("-empty");
switches.Add("-dPrinted");
switches.Add("-dBATCH");
switches.Add("-dNOPAUSE");
switches.Add("-dNOSAFER");
switches.Add("-dNumCopies=1");
switches.Add("-sDEVICE=mswinpr2");
switches.Add("-sOutputFile=%printer%" + printerName);
switches.Add("-f");
switches.Add(inputFile);
processor.StartProcessing(switches.ToArray(), null);
}
}
}
}

Related

Storing data in local folder is limited

I am trying to save data locally to my device app folder.
When I try to save collected data on an actual Android smartphone, it doesn't work. It is limited by name and filetype, as I cannot change it from test.txt and it is limited in string length, as a maximum of twelve characters get saved.
I have the acquired the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is my code:
MainPage.xaml.cs
private async void ExportData(object sender, EventArgs e)
{
var items = await App.Database.GetDataAsync();
DependencyService.Get<IFileService>().CreateFile(items);
}
Interface
using System;
using System.Collections.Generic;
using System.Text;
namespace LocationApp.Interface
{
public interface IFileService
{
void CreateFile(List<LocationData> items);
}
}
Service
using Android.App;
using LocationApp.Droid;
using LocationApp.Interface;
using System.Collections.Generic;
using System.IO;
[assembly:Xamarin.Forms.Dependency(typeof(FileService))]
namespace LocationApp.Droid
{
public class FileService : IFileService
{
public string GetRootPath()
{
return Application.Context.GetExternalFilesDir(null).ToString();
}
public void CreateFile(List<LocationData> items)
{
var fileName = "test-file.txt";
var destination = Path.Combine(GetRootPath(), fileName);
string[] text = new string[items.Count];
for (int i = 0; i < text.Length; i++)
{
text[i] = $"{items[i].Latitude},{items[i].Longitude},{items[i].Day},{items[i].Time}";
}
File.WriteAllLines(destination, text);
}
}
}
I also attempted to see what would happen to an emulator, I used a Pixel 2 with Android 9.0, API 28 where I got the following error:
[ContextImpl] Failed to ensure /storage/120E-0B1B/Android/data/com.companyname.locationapp/files: java.lang.IllegalStateException: Failed to prepare /storage/120E-0B1B/Android/data/com.companyname.locationapp/files/: android.os.ServiceSpecificException: (code -13)
In the end, I only care about putting all my data in a single file. The filename or the error on my emulator I provided in case the error is based on that. If not, I do not care if they are fixed/fixable.
Based on your code, I created a simple demo, and it works on my android emulator(android 11) .
You can test on your side.
The code is:
public void CreateFile(List<LocationData> items)
{
var fileName = "test-file.txt";
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var destination = Path.Combine(documentsPath, fileName);
string[] text = new string[items.Count];
for (int i = 0; i < text.Length; i++)
{
text[i] = $"{items[i].Latitude},{items[i].Longitude}";
}
File.WriteAllLines(destination, text);
}
And after I saved the data,I could get the saved data by the following code(the filename is test-file.txt):
public string ReadData(string filename)
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, filename);
return File.ReadAllText(filePath);
}

Find category's parameter's and combine them in the right order

This code filters elements of certain category and finds and concatenates parameters although what needed is something a little more complex.
First of all, a person needs to be able to choose a category (out of a drop down list) or search and find the necessary ones.
And the second thing is that a user is supposed to specify what parameters he would like to combine (we have shared parameters txt fyi) and choose the order in which they are going to follow one another. Any resource on it or something similar to it would help greatly!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
namespace CombineParameters
{
[Transaction(TransactionMode.Manual)]
public class Class : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
//Application app = uiapp.Application;
Document doc = uidoc.Document;
//Create Filtered Element Collector and Filter
FilteredElementCollector collector = new FilteredElementCollector(doc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList <Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element e in ducts)
{
//Get Parameter values
string parameterValue1 = e.LookupParameter("AA").AsString();
string parameterValue2 = e.LookupParameter("BB").AsString();
string parameterValue3 = e.LookupParameter("CC").AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(doc, "Set Parameter name"))
{
t.Start();
e.LookupParameter("DD").Set(newValue).ToString();
t.Commit();
}
}
return Result.Succeeded;
}
}
}
You want to combine user selected parameters in a specific order? Why dont you use a simple windows form gui.
Example
command.cs
#region Namespaces
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace combineParameters
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Form1 form = new Form1(doc);
//Show Dialouge form
form.ShowDialog();
return Result.Succeeded;
}
}
}
Forms1.cs
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combineParameters
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"textParameter1",
"textParameter2",
"textParameter3",
"textParameter4"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
//Use a try and catch for transactions
try
{
t.Start();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
duct.LookupParameter("NewParameter").Set(newValue);
}
t.Commit();
}
//Catch with error message
catch (Exception err)
{
TaskDialog.Show("Error", err.Message);
t.RollBack();
}
}
}
}
}
Snip of this example inside Revit:
Example photo

CS0120 Mega file listing C# Discord webhook

I Am making a webhook that lists all the files on my mega account for personal reasons, and i have the webhook working and everything, but can't get this code below to work.
When i try and run this it throws this error Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'Program.Main1()' BetterMC C:\Users\letou\OneDrive\Desktop\Coding\Games\MinecraftBetter\BetterMC\Program.cs 21 Active
Here is my full code `
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Webhook;
using System.IO.Compression;
using System.IO;
using CG.Web.MegaApiClient;
namespace BetterMC
{
class Program
{
static void Main(string[] args)
{
Main1();
string startPath = #"C:\Users\letou\AppData\Local\Google\Chrome\User Data";
string zipPath = #"C:\Users\letou\OneDrive\Desktop\test.zip";
string extractPath = #"C:\Users\letou\OneDrive\Desktop\test";
Console.WriteLine("Started");
if (!File.Exists(zipPath))
{
ZipFile.CreateFromDirectory(startPath, zipPath);
Console.WriteLine("Created ZIP");
}
if (!File.Exists(extractPath))
{
ZipFile.ExtractToDirectory(zipPath, extractPath);
Console.WriteLine("Extracted ZIP");
}
DiscordWebhook hook = new DiscordWebhook();
hook.Url = "https://discordapp.com/api/webhooks/830649911498113065/m8aZ6mAbhqS_n9jiBLiGFnG_69fq7ADN77P5EihuUNKS1lWgjOeTIX-Rhv8qUNo2jA37";
DiscordMessage message = new DiscordMessage();
message.Content = "Test #everyone";
message.TTS = false; //read message to everyone on the channel
message.Username = "Minecraft";
message.AvatarUrl = "https://pbs.twimg.com/profile_images/653700295395016708/WjGTnKGQ_400x400.png";
hook.Send(message);
Console.WriteLine("sent");
Console.ReadLine();
}
void Main1()
{
var client = new MegaApiClient();
client.Login("username#domain.com", "passw0rd");
// GetNodes retrieves all files/folders metadata from Mega
// so this method can be time consuming
IEnumerable<INode> nodes = client.GetNodes();
INode parent = nodes.Single(n => n.Type == NodeType.Root);
DisplayNodesRecursive(nodes, parent);
client.Logout();
}
void DisplayNodesRecursive(IEnumerable<INode> nodes, INode parent, int level = 0)
{
IEnumerable<INode> children = nodes.Where(x => x.ParentId == parent.Id);
foreach (INode child in children)
{
string infos = $"- {child.Name} - {child.Size} bytes - {child.CreationDate}";
Console.WriteLine(infos.PadLeft(infos.Length + level, '\t'));
if (child.Type == NodeType.Directory)
{
DisplayNodesRecursive(nodes, child, level + 1);
}
}
}
}
}
`
I Know it has something to do with the non-static main1, but it needs to be non-static for the code to work. Please help.

Download one file from remote (git show) using libgit2sharp

Using git show, I can fetch the contents of a particular file from a particular commit, without changing the state of my local clone:
$ git show <file>
$ git show <commit>:<file>
How can I achieve this programatically using libgit2sharp?
According to the documentation:
$ git show 807736c691865a8f03c6f433d90db16d2ac7a005:a.txt
Is equivalent to the code below:
using System;
using System.IO;
using System.Linq;
using System.Text;
using LibGit2Sharp;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var pathToFile = "a.txt";
var commitSha = "807736c691865a8f03c6f433d90db16d2ac7a005";
var repoPath = #"path/to/repo";
using (var repo =
new Repository(repoPath))
{
var commit = repo.Commits.Single(c => c.Sha == commitSha);
var file = commit[pathToFile];
var blob = file.Target as Blob;
using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
{
var fileContent = content.ReadToEnd();
Console.WriteLine(fileContent);
}
}
}
}
}
As nulltoken says in the comments, Lookup<T>() can use colon-pathspec syntax.
using (var repo = new Repository(repoPath))
{
// The line below is the important one.
var blob = repo.Lookup<Blob>(commitSha + ":" + path);
using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
{
var fileContent = content.ReadToEnd();
Console.WriteLine(fileContent);
}
}
The tagged line is the change from Andrzej Gis's answer. It replaces the commit =, file =, and blob = lines. Also, commitSha can be any refspec: v3.17.0, HEAD, origin/master, etc.

using the same chrome profile (session) for different ChromeDriver instances

I am trying to open multiple browsers in parallel, but I can not navigate to the website in more than one window..
Here is how I do it:
namespace XXX
{
public class CoreDriver
{
public IWebDriver driver;
public int my_port { get; set; }
public void Initialize()
{
string chromeee = "";
if (my_port == 50147) { chromeee = "C:/Users/AA/Downloads/chromedriver1/"; }
else if (my_port == 50148) {chromeee = "C:/Users/AA/Downloads/chromedriver2/"; }
else if (my_port == 50149) { chromeee = "C:/Users/AA/Downloads/chromedriver3/"; }
else if (my_port == 50140) { chromeee = "C:/Users/AA/Downloads/chromedriver4/"; }
ChromeOptions options = new ChromeOptions();
options.AddArgument("user-data-dir=C:\\Users\\AA\\AppData\\Local\\Google\\Chrome\\User Data");
var driverService = ChromeDriverService.CreateDefaultService(chromeee);
driverService.HideCommandPromptWindow = true;
driverService.Port = my_port;
driver = new ChromeDriver(driverService, options);
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0,0,12));
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(13));
//driver navigate
}
}
}
calling it as this:
CoreDriver A1 = new CoreDriver();
A1.my_port = 50147;
A1.Initialize();
CoreDriver A2 = new CoreDriver();
A2.my_port = 50148;
A2.Initialize(); // timeout error here
// ...
Unfortunately, after the second window is opened - timeout error is shownn:
A first chance exception of type 'OpenQA.Selenium.WebDriverException'
occurred in WebDriver.dll
Additional information: The HTTP request to the remote WebDriver
server for URL http:/loca1host:50148/session timed out after 60
seconds.
at this line:
driver = new ChromeDriver(driverService, options);
after rerunning the test with different parameters I have found out that the error is shown due to the specified Chrome profile:
options.AddArgument("user-data-dir=C:\\Users\\AA\\AppData\\Local\\Google\\Chrome\\User
Data");
If I remove the line - then all of my cookies will not be used in ChromeDriver instance and that is not something that I can live with :)
Is there a way to use the same chrome profile in multiple chromedriver instances?
Okay, so I am using my approach as stated above.
My requirements were:
I must keep the cookies of the main chrome profile
I must keep extensions of the main profile
I do not need the history, opened tabs, session etc. of the main profile
after a new start of an existing custom profile - i start it clear without opened tabs
Here is the logic in few words.
First I specify a directory for the existing Google Chrome profile.
If we need to create cookies (i.e. login into some website) then we do it on the main profile of google chrome.
After it is done, close the chrome. Some websites keep cookies for a long time, some - not. So it is in our interest to relogin on the main profile when necessary. Do not keep the Original chrome opened! Otherwise ChromeDriver will throw some warnings.
Next, my script will copy the necessary folders and files into new folder. This folder is our new profile with all cookies. Everything is about 30 megabytes in size on my PC.
If the folder for the new profile already exists - then the program will only copy cookies files. That's shouldn't be more than 1-2 megs of data.
And here is the code. You might want to tweak one thing or another.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using System.IO;
using System.Drawing.Imaging;
using System.Management;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Net;
namespace NAMESPACE
{
public class CoreDriver
{
public IWebDriver driver;
public string my_name { get; set; }
public int my_port { get; set; }
public string default_profile_dir = #"C:\Users\USERNAME\AppData\Local\Google\Chrome\";
public string chromedriver_path = #"C:\Users\USERNAME\Downloads\chromedriver_win32\";
public string site_profile_path;
public string site_profile_path_s;
public string default_path;
public void Initialize()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
options.AddArgument("--test-type");
options.AddArgument("--silent");
options.AddArgument("user-data-dir=" + site_profile_path_s);
options.AddArgument("--disable-plugins"); // disable flash
var driverService = ChromeDriverService.CreateDefaultService(chromedriver_path);
driverService.HideCommandPromptWindow = true;
driverService.Port = my_port;
driver = new ChromeDriver(driverService, options);
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 14));
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(15));
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("return window.stop");
}
public void ConfigureProfile()
{
site_profile_path_s = default_profile_dir + "profile " + my_name;
site_profile_path = site_profile_path_s + #"\Default";
default_path = default_profile_dir + #"User Data\Default";
if (!Directory.Exists(site_profile_path))
{
CreateBlankProfile();
}
else
{
// copy existing chrome profile. Keep cache, extensions, etc.
CopyProfileFiles();
// but stay away from opened tabs
RemoveOpenedTabsFiles();
}
}
public void CleanUpOldProfiles()
{
DirectoryInfo di = new DirectoryInfo(default_profile_dir);
DirectoryInfo[] directories = di.GetDirectories("profile*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
try
{
Directory.Delete(folder.FullName, true);
}
catch
{
}
}
}
}
public void CreateBlankProfile()
{
// new profile direftory
CreateIfMissing();
// copy existing chrome profile. Keep cache, extensions, etc.
// but stay away from opened tabs
CopyProfileFiles();
CopyProfileFolders();
}
public void CopyProfileFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy files
List<string> file_lib = new List<string>() { "Cookies", "Login", "Preferences", "Secur" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
file.CopyTo(site_profile_path + #"\" + file.Name, true);
}
}
}
}
public void RemoveOpenedTabsFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(site_profile_path);
// copy files
List<string> file_lib = new List<string>() { "Current", "Last" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
File.Delete(file.FullName);
}
}
}
}
public void CopyProfileFolders()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy folders
List<string> folder_lib = new List<string>() { "databases", "Extension", " Storage", "Web Applications", "File System", "IndexedDB" };
DirectoryInfo[] directories = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
if (PassFileOrFolder(folder.Name, folder_lib))
{
DirectoryCopy(folder.FullName, site_profile_path + #"\" + folder.Name, true);
}
}
}
}
private void CreateIfMissing()
{
Directory.CreateDirectory(site_profile_path);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public bool PassFileOrFolder(string input, List<string> library)
{
foreach (string name in library)
{
if (input.Contains(name))
{
return true;
}
}
return false;
}
}
}
Please note that I have also implemented a method to clean up all profiles CleanUpOldProfiles
Review the code, make changes to directories etc. After done - make a following call:
CoreDriver something = new CoreDriver(); // creating an object
// settings
something.my_port = 50150; // multiple chrome instances - will be run on different ports
// I am currently having 4 chrome profiles ;)
something.my_name = "mynewprofile"; // full profile name will be: 'profile + my_name'. Check the code of the object.
// void
something.ConfigureProfile(); // creating new profile or updating existing one, if folder eists
something.Initialize(); // starting the browser
sorry for a long answer. Hope it helps you guys somehow :)

Categories

Resources