To automatically save a PDF or XPS file in a specific network location using C#, you can use the System.IO.FileInfo class to create a FileInfo object for the desired file path and then use the SaveAs method to save the file. Here's an example using a PDF printer to generate a PDF and saving it to a network location:
using System;
using System.Drawing;
using System.IO;
using System.Printing;
using System.Windows.Forms.Design;
public class SavePdfToNetwork
{
public static void Main()
{
// Create a new PDF document
PrintDocument printDocument = new PrintDocument();
PrintDocumentEventArgs printEventArgs = new PrintDocumentEventArgs(printDocument, new PrintPageEventArgs(printDocument.CreatePrinterSettings(), false));
// Add content to the PDF document
printDocument.PrintPage += (sender, args) =>
{
// Draw content on the page
using (Graphics graphics = args.Graphics)
{
graphics.DrawString("Hello, World!", new Font("Arial", 12), Brushes.Black, new RectangleF(0, 0, args.MarginBounds.Width, args.MarginBounds.Height));
}
};
// Print the document
printDocument.Print();
// Save the PDF to a network location
string networkPath = @"\\server\share\folder\file.pdf";
printDocument.PrintController.PrintDocument(printDocument, false);
printDocument.Save();
printDocument.DocumentName = "MyDocument";
printDocument.Print();
// Save the PDF as a file
FileInfo fileInfo = new FileInfo(networkPath);
printDocument.PrintController.PrintDocument(printDocument, false);
printDocument.Save();
printDocument.DocumentName = "MyDocument";
using (FileStream fileStream = fileInfo.Create())
{
printDocument.PrintController.PrintControllerStream.CopyTo(fileStream);
}
}
}
Replace \\server\share\folder\file.pdf with your desired network file path. This example uses a simple text string as content, but you can replace it with your own content as needed.
This code generates a single-page PDF and saves it to a network location. It uses the PrintDocument class to create a PDF, and the PrintControllerStream to write the PDF data to a file.
References: