Convert PDF to SVG with C#
This code uses the OpenService
and CloseService
methods from the PDF Converter API DocumentConverterServiceClient
sample code and converts a multipage PDF file to a collection of Scalable Vector Graphics (SVG) files:
/// <summary> /// Convert a PDF to a collection of SVG files. /// </summary> /// <param name="ServiceURL"></param> /// <param name="sourceFileName"></param> /// <param name="targetFolder"></param> static void PDFToSVG(string ServiceURL, string sourceFileName, string targetFolder) { DocumentConverterServiceClient client = null; try { // Create minimum `OpenOptions` object. OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
// Create minimum `PatternHighlightSettings`. PDFToOfficeSettings pDFToOfficeSettings = new PDFToOfficeSettings(); pDFToOfficeSettings.OfficeType = OfficeTypes.SVG; pDFToOfficeSettings.PageRange = "*"; // Create target folder if required. if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } // ** Read the source file into a byte array. byte[] sourceFile = File.ReadAllBytes(sourceFileName);
// ** Open the service and configure the bindings. client = OpenService(ServiceURL);
// Convert the pages to SVG files. BatchResults batchResults = client.PDFToSVG(sourceFile,openOptions, pDFToOfficeSettings);
// If results are returned. if (batchResults != null && batchResults.Results != null && batchResults.Results.Length>0) { // For each result. foreach(BatchResult result in batchResults.Results) { // Get the filename. string filename = result.FileName; string destinationFileName = Path.GetFullPath(Path.Combine(targetFolder, filename)); // Write the file content to a file using (FileStream fs = File.Create(destinationFileName)) { fs.Write(result.File, 0, result.File.Length); fs.Close(); } Console.WriteLine("File converted to " + destinationFileName);
} } else { Console.WriteLine("Nothing returned"); }
} catch (FaultException<WebServiceFaultException> ex) { Console.WriteLine($"FaultException occurred: ExceptionType: {ex.Detail.ExceptionType.ToString()}"); Console.WriteLine(); Console.WriteLine($"Error Detail: {string.Join(Environment.NewLine, ex.Detail.ExceptionDetails)}"); Console.WriteLine($"Error message: {ex.Message}"); Console.WriteLine(); Console.WriteLine($"Error reason: {ex.Reason}"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Data.ToString()); } finally { if (client != null) { CloseService(client);
} } }