PdfToGrayscaleTiff.vb
C# VB
'''' This code is part of Document Solutions for PDF .NET demos.'' Copyright (c) MESCIUS inc. All rights reserved.''Imports System.IOImports System.DrawingImports System.Collections.GenericImports GrapeCity.Documents.PdfImports GrapeCity.Documents.ImagingImports GrapeCity.Documents.Drawing
Public Class PdfToGrayscaleTiff Public Function CreatePDF(ByVal stream As Stream) As Integer ' Arbitrary target DPI for the generated TIFF, adjust as needed: Const targetDPI As Integer = 200
Dim inputDoc = New GcPdfDocument() Using fs = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf")) inputDoc.Load(fs)
Using ms As New MemoryStream() Using bmp As New GcBitmap() ' NOTE: to produce a TIFF disk file, you would create a GcTiffWriter ' with the file path as the parameter. But due to the demo browser requirements, ' we create a GcTiffWriter on a memory stream instead: ' Using tiffWriter As New GcTiffWriter("result.tiff") Using msTiff As New MemoryStream() Using tiffWriter As New GcTiffWriter(msTiff) For Each pIn In inputDoc.Pages ' Save each PDF page as PNG with target resolution: ms.Position = 0 pIn.SaveAsPng(ms, New SaveAsImageOptions() With {.Resolution = targetDPI}) ms.Position = 0 bmp.Load(ms) ' Load the PNG into GcBitmap, apply in-place grayscale effect, ' convert to grayscale bitmap and append it to the TIFF: bmp.ApplyEffect(GrayscaleEffect.Get()) Using gbmp = bmp.ToGrayscaleBitmap() tiffWriter.AppendFrame(gbmp) End Using Next End Using ' At this point tiffWriter has the newly created TIFF. If it was created on ' a disk file, that file would contain the TIFF when tiffWriter is disposed. ' ' To use this sample in the demo browser, we have to convert the TIFF ' back to a PDF that is returned to the controller. msTiff.Position = 0 Dim doc = New GcPdfDocument() Using tiffReader As New GcTiffReader(msTiff) Dim disposables As New List(Of IDisposable)() For Each tp In tiffReader.Frames Dim img = tp.ToImage(ImageBinding.InMemoryData) Dim pOut = doc.Pages.Add(New SizeF(img.Width / img.HorizontalResolution * 72, img.Height / img.VerticalResolution * 72)) pOut.Graphics.DrawImage(img, pOut.Bounds, Nothing, ImageAlign.Default) disposables.Add(img) Next ' Save the PDF: doc.Save(stream) ' We can only dispose images after saving the PDF: disposables.ForEach(Sub(d_) d_.Dispose()) Return doc.Pages.Count End Using End Using End Using End Using End Using End FunctionEnd Class