How can I print XPS without dialog? - c#

I try to print to XPS printer (it's not my default printer), but the program opens me a dialog.
Can I skip the dialog? This is the code:
pSettings = new PrinterSettings();
pSettings.PrintFileName = "test.xps";
RawPrinterHelper.SendStringToPrinter(pSettings.PrinterName, toSend);
spcn = new StandardPrintController();
printDocument1.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
printDocument1.PrintController = spcn;
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.Print();

You can print PDF to XPS without a dialog using Aspose API
Aspose API
//Create PdfViewer object and bind PDF file
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.OpenPdfFile("input.pdf");
//Set PrinterSettings and PageSettings
System.Drawing.Printing.PrinterSettings printerSetttings = new System.Drawing.Printing.PrinterSettings();
printerSetttings.Copies = 1;
printerSetttings.PrinterName = "Microsoft XPS Document Writer";
//Set output file name and PrintToFile attribute
printerSetttings.PrintFileName = "C:\\tempfiles\\printoutput.xps";
printerSetttings.PrintToFile = true;
**//Disable print page dialog**
**pdfViewer.PrintPageDialog = false;**
//Pass printer settings object to the method
pdfViewer.PrintDocumentWithSettings(printerSetttings);
pdfViewer.ClosePdfFile();

Related

Let user select any printer to print a report

This code works well printing to default printer, but how I can do to display the Print Dialog to allow the user to select any printer?
var report = new ReportDocument();
report.Load(System.Windows.Forms.Application.StartupPath + #"\Reports\RouteSlip.rpt");
report.Database.Tables[0].SetDataSource(dtData.Tables[0]);
var prntSettings = new PrinterSettings
{
Copies = 1,
Collate = false,
};
report.PrintToPrinter(prntSettings, new PageSettings(), false);

Spire.PDF prints pdf only in grayscale

I am using the free version of Spire.PDF to print a local pdf file but the print is in grayscale even though the pdf file is in color. Here is my code
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(fileName);
doc.ColorSpace = PdfColorSpace.RGB;
PrintDialog dialogPrint = new PrintDialog();
dialogPrint.AllowPrintToFile = true;
dialogPrint.AllowSomePages = true;
dialogPrint.PrinterSettings.MinimumPage = 1;
dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
dialogPrint.PrinterSettings.FromPage = 1;
dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
if (dialogPrint.ShowDialog() == DialogResult.OK)
{
//Set the pagenumber which you choose as the start page to print
doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
//Set the pagenumber which you choose as the final page to print
doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
//Set the name of the printer which is to print the PDF
doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
PrintDocument printDoc = doc.PrintDocument;
printDoc.DefaultPageSettings.Color = true;
dialogPrint.Document = printDoc;
printDoc.Print();
}
I have checked dialogPrint.PrinterSettings.SupportsColor returns true

PDFClown .NET Open a Windows Explorer instead of specifying path

Currently I have this test code
File file = new File();
Document document = file.Document;
Page page = new Page(document);
document.Pages.Add(page);
PrimitiveComposer composer = new PrimitiveComposer(page);
composer.SetFont(new StandardType1Font(document, StandardType1Font.FamilyEnum.Courier, true, false), 32);
composer.ShowText("Hello World!", new PointF(32, 48));
composer.Flush();
file.Save("test.pdf", SerializationModeEnum.Incremental);
System.Diagnostics.Process.Start("explorer", System.IO.Directory.GetParent(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).ToString());
How can I open a general windows explorer save as prompt instead of saving to the hard code path "test.pdf"? (In file.save())
Thanks
Use SaveFileDialog for that:
https://msdn.microsoft.com/en-us/library/sfezx97z(v=vs.110).aspx
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "PDF File|*.pdf";
saveFileDialog1.Title = "Save PDF";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
file.Save(saveFileDialog1.FileName, SerializationModeEnum.Incremental);
}

Where should files used in a saved file template be placed?

I'm publishing a windows form application which allows the user to save a PDF of the information they input. The PDF contains 2 images (logo.png & name.png). I'm currently storing those pictures in my bin>Debug folder.
My question is, if I publish the program, will the PDF still have access to these images or do they need to be placed in another folder in order for the PDF to generate correctly?
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "New (*.pdf)|*.pdf|All Files (*.*|*.*";
dlg.AddExtension = true;
dlg.DefaultExt = ".pdf";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(dlg.FileName.ToString(), FileMode.Create));
doc.Open();//Open Document to write
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("logo.png");
logo.ScalePercent(45f);
logo.SetAbsolutePosition(doc.PageSize.Width - 105f - 72f, doc.PageSize.Height - -15f - 216.6f);
doc.Add(logo);
iTextSharp.text.Image name = iTextSharp.text.Image.GetInstance("name.png");
name.ScalePercent(95f);
name.SetAbsolutePosition(doc.PageSize.Width - 500f - 72f, doc.PageSize.Height - -55f - 216.6f);
doc.Add(name);
var titleFont = FontFactory.GetFont("Times New Roman", 24);
var headerFont = FontFactory.GetFont("Times New Roman", 20);
var bodyFont = FontFactory.GetFont("Times New Roman", 16);
var fineFont = FontFactory.GetFont("Times New Roman", 8);
//Write pdf content
doc.Close();//Close document
I would just add the image as a resource to your project, this will bake it into the DLL/EXE itself. Right-click your project and select Properties and then click on Resources. Click Add Resource and then Add Existing File. Select your image and optionally rename it. Then in your code you can access it using its fully qualified name:
var img = WindowsFormsApplication1.Properties.Resources.logo;
var logo = iTextSharp.text.Image.GetInstance(img, BaseColor.WHITE);
doc.Add(logo);
Replace WindowsFormsApplication1 with whatever namespace you have setup for your project.

How to create PDF file in C#.Net

I want to create pdf file in c#. Pdf file contains text files and images. I want to arrange that text files and images at runtime and after arranging I want to save it as .pdf file. Please help me.
Thanks in advance.
You should try: http://itextpdf.com/
I net there is a lot examples how to use it for purpose you described.
Try This,
you need to download wnvhtmlconvert.dll
to use pdfconverter class
--html side
<table id="tbl" runat="server" style="width: 940px;" cellpadding="0" cellspacing="0" border="0">
<tr id="tr" runat="server">
<td id="td" runat="server" align="center" valign="top"></td>
</tr>
</table>
--code side
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Collections.Generic
Imports System.Drawing
Public Sub ExportQuickScToPDF()
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Dim pdfByte As [Byte]() = Nothing
Dim strPageBreak As String = "<br style=""page-break-before: always"" />"
Dim lblPageBreak As New Label
Dim lbltext As New Label
lblPageBreak.Text = strPageBreak
'add image
Dim imgqsc As New System.Web.UI.WebControls.Image
imgqsc.ImageUrl = "path"
td.Controls.Add(imgqsc)
tbl.RenderControl(htmlWrite)
'add text
lbltext.Text = "text"
lbltext.RenderControl(htmlWrite)
'add page break
lblPageBreak.Text = "text"
lblPageBreak.RenderControl(htmlWrite)
Dim objPdf As New PdfConverter()
objPdf.LicenseKey = "license key with dll"
objPdf.PdfFooterOptions.ShowPageNumber = False
objPdf.PdfFooterOptions.FooterTextFontSize = 10
objPdf.PdfDocumentOptions.ShowHeader = True
objPdf.PdfDocumentOptions.ShowFooter = False
objPdf.PdfDocumentOptions.EmbedFonts = True
objPdf.PdfDocumentOptions.LiveUrlsEnabled = True
objPdf.RightToLeftEnabled = False
objPdf.PdfSecurityOptions.CanPrint = True
objPdf.PdfSecurityOptions.CanEditContent = True
objPdf.PdfSecurityOptions.UserPassword = ""
objPdf.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape
objPdf.PdfDocumentInfo.CreatedDate = DateTime.Now
objPdf.PdfDocumentInfo.AuthorName = ""
pdfByte = objPdf.GetPdfBytesFromHtmlString(stringWrite.ToString())
Session("pdfByte") = pdfByte
End Sub
you need to add reference of that dll
and also import it in code
Imports Winnovative.WnvHtmlConvert
You can use iTextSharp. There are some other libraries as well. Click here.
To create PDF i use 'iText' library, is open and it's really easy to use.
You can download iText here.
Me votes for iText too :) Rather easy and comfortable to start with:
string pdfFilename = #"c:\temp\test.pdf";
string imageFilename = #"C:\map.jpg";
// Create PDF writer, document and image to put
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageFilename);
Document doc = new Document();
PdfWriter pdfW = PdfWriter.GetInstance(doc, new FileStream(pdfFilename, FileMode.Create));
// Open created PDF and insert image to it
doc.Open();
doc.Add(image);
doc.Close();
// paste on button click
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("This is test file"); // hardcode text
pdfDoc.Add(new Phrase(this.lbl1.Text.Trim())); //from label
pdfDoc.Add(new Phrase(this.txt1.Text.Trim())); //from textbox
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Try to download and add the reference of bytescout then use this code :
using System.Diagnostics;
using Bytescout.PDF;
namespace WordSpacing
{
/// <summary>
/// This example demonstrates how to change the word spacing.
/// </summary>
class Program
{
static void Main()
{
// Create new document
Document pdfDocument = new Document();
pdfDocument.RegistrationName = "demo";
pdfDocument.RegistrationKey = "demo";
// Add page
Page page = new Page(PaperFormat.A4);
pdfDocument.Pages.Add(page);
Canvas canvas = page.Canvas;
Font font = new Font("Arial", 16);
Brush brush = new SolidBrush();
StringFormat stringFormat = new StringFormat();
// Standard word spacing
stringFormat.WordSpacing = 0.0f;
canvas.DrawString("Standard word spacing 0.0", font, brush, 20, 20, stringFormat);
// Increased word spacing
stringFormat.WordSpacing = 5.0f;
canvas.DrawString("Increased word spacing 5.0", font, brush, 20, 50, stringFormat);
// Reduced word spacing
stringFormat.WordSpacing = -2.5f;
canvas.DrawString("Reduced word spacing -2.5", font, brush, 20, 80, stringFormat);
// Save document to file
pdfDocument.Save("result.pdf");
// Cleanup
pdfDocument.Dispose();
// Open document in default PDF viewer app
Process.Start("result.pdf");
}
}
}
At first get reference, then try to use this code
using System.Runtime.InteropServices;
[DllImport("shell32.dll")]
public static extern int ShellExecute(int hWnd,
string lpszOp, string lpszFile, string lpszParams, string lpszDir,int FsShowCmd);
ShellExecute(0, "OPEN", args[0] + ".pdf", null, null, 0);
Or use this sharppdf or this itextsharp

Categories

Resources