当我尝试在C#WinForm应用程序中将彩色pdf或图像转换为黑白或灰度pdf iTextSharp时,它不起作用,并且透明图像也有问题。转换时,它将背景变为黑色,以获得透明图像。我正在使用以下代码首先将其转换为pdf
string urlpdf = output.Replace(".png", ".pdf").Replace(".jpeg", ".pdf").Replace(".jpg", ".pdf").Replace(".PNG", ".pdf").Replace(".JPEG", ".pdf").Replace(".JPG", ".pdf");
using (FileStream fs = File.Open(urlpdf, FileMode.OpenOrCreate))
{
PdfWriter PdfIns = PdfWriter.GetInstance(docPNG, fs);
docPNG.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
if (comboBox8.SelectedIndex == 1)
{
pdfImage.ScaleToFit(rec);
pdfImage.SetAbsolutePosition((docPNG.PageSize.Width - pdfImage.ScaledWidth) / 2, (docPNG.PageSize.Height - pdfImage.ScaledHeight) / 2);
}
else
{
pdfImage.ScalePercent((float)numericUpDown4.Value);
}
docPNG.Add(pdfImage);
docPNG.CloseDocument();
docPNG.Close();
}
,然后按如下所示灰度或黑白-
iTextSharp.text.pdf.converter.PdfContentToGrayscaleConverter grayscaleConverter = new iTextSharp.text.pdf.converter.PdfContentToGrayscaleConverter();
using (PdfReader reader = new PdfReader(inputFile))
{
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, fsOutput);
document.Open();
PdfContentByte cb = writer.DirectContent;
int numberOfPages = reader.NumberOfPages;
try
{
for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++)
{
iTextSharp.text.Rectangle pageSizeWithRotation = reader.GetPageSizeWithRotation(pageNumber);
document.SetPageSize(pageSizeWithRotation);
document.NewPage();
int SecondChance = 0;
conti: ///continue again
try
{
// >>> CONVERT CURRENT PAGE TO GRAYSCALE
grayscaleConverter.Convert(reader, pageNumber);
// <<<<
}
catch
{
if (SecondChance == 0)
{
SecondChance++;
goto conti; ///junmp to conti
}
}
PdfImportedPage pip = writer.GetImportedPage(reader, pageNumber);
if (pageSizeWithRotation.Rotation == 90 || pageSizeWithRotation.Rotation == 270)
{
cb.AddTemplate(pip, 0, -1f, 1f, 0, 0, pageSizeWithRotation.Height);
}
else
{
cb.AddTemplate(pip, 1f, 0, 0, 1f, 0, 0);
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
cb.PdfDocument.Close();
document.Close(); document.Dispose(); document = null;
writer.Close(); writer.Dispose(); writer = null;
reader.Close(); reader.Dispose();
}
}