I’m having problems in my program. Firstly, I write data in a already existing Excel Workbook, then I convert the file from XLSX to PDF.
The data is being inserted correctly into the Excel every time, but when it reaches the line of the conversion (“pdf.ConvertFile(excelFile, pdfFile);”), the program gives me an Exception (“System.Exception: ‘Text cannot contain characters with code less than 32 (space). For these characters use SpecialCharacter instance.'”).
I already tried every Regex or input string, it always gives me the same advice. When I initiate the program without inserting something into the Excel via EPPlus, the conversion works just fine.
I believe that the way EPPlus insert strings into the sheet uses invalid characters, but I don’t know how to fix it.
I’m using EPPlus to insert data into the sheet, SautinSoft to make the XLSX2PDF conversion and PdfSharp to delete a page of the pdf that is blank. Already tried Aspose and the program worked just like I wanted, but the watermark is too scandalous.
using System;
using System.IO;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf;
using SautinSoft;
using OfficeOpenXml;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;
namespace ToPDF
{
class Program
{
static void Main(string[] args)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
string ExcelPath = "/Documents/Planilhas/Plant.xlsx";
Program p = new Program();
using (var package = new ExcelPackage(new FileInfo(ExcelPath)))
{
ExcelWorksheet capa = package.Workbook.Worksheets[0];
ExcelWorksheet UNS = package.Workbook.Worksheets[1];
ExcelWorksheet Sheet1 = package.Workbook.Worksheets[2];
p.InsertInto(Sheet1, "C4", $"{DateTime.Now.Year}/{DateTime.Now.Month}");
package.Save();
}
p.Xlsx2Pdf(ExcelPath);
}
private void InsertInto(ExcelWorksheet worksheet, string celula, string valor)
{
string cleanValor = CleanInput(valor);
worksheet.Cells[celula].Value = cleanValor;
}
private static string CleanInput(string input)
{
return Regex.Replace(input, @"[x00-x1F]", "");
}
private void Xlsx2Pdf(string excelFile)
{
ExcelToPdf pdf = new ExcelToPdf();
pdf.OutputFormat = SautinSoft.ExcelToPdf.eOutputFormat.Pdf;
string pdfFile = Path.ChangeExtension(excelFile, ".pdf");
pdf.PageStyle.PageScale.FitByHeight();
pdf.ConvertFile(excelFile, pdfFile);
PdfDocument p = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Modify);
int page = 1;
p.Pages.RemoveAt(page);
p.Save(pdfFile);
}
}
}
I already tried Aspose.cells and it worked, but the watermark was too big. When I don’t “package.Save()” the changes into the sheet, the conversion works. I already tried multiple REGEX methods and strings treatments, but the problem seams to be on the EPPlus’ method itself
user26650123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.