Skip to content

Commit ffefa47

Browse files
Merge pull request #399 from SyncfusionExamples/ES-850687-Replace-DISPLAYBARCODE-to-image
ES-850687- Add the sample Replace-DISPLAYBARCODE-to-image
2 parents d313f5a + 7376b4c commit ffefa47

File tree

5 files changed

+279
-0
lines changed

5 files changed

+279
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.31911.196
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Replace-DISPLAYBARCODE-to-image", "Replace-DISPLAYBARCODE-to-image\Replace-DISPLAYBARCODE-to-image.csproj", "{D3AF529E-DB54-4294-A876-DD42E1E472D0}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {58137FF9-5AE1-4514-9929-3A8A7DA1DFEB}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
using Syncfusion.DocIO.DLS;
2+
using Syncfusion.DocIO;
3+
using Syncfusion.Pdf.Barcode;
4+
using Syncfusion.Pdf.Graphics;
5+
using System.Text.RegularExpressions;
6+
using SizeF = Syncfusion.Drawing.SizeF;
7+
using System.Collections.Generic;
8+
using System.IO;
9+
using System;
10+
using Syncfusion.DocIORenderer;
11+
using Syncfusion.Pdf;
12+
13+
namespace Replace_DISPLAYBARCODE_to_image
14+
{
15+
internal class Program
16+
{
17+
static void Main(string[] args)
18+
{
19+
//Open the Word document from a file stream
20+
using (FileStream docStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read))
21+
{
22+
//Load the Word document
23+
using (WordDocument document = new WordDocument(docStream, FormatType.Docx))
24+
{
25+
//Replace specific barcode fields in the document with generated barcode images
26+
ReplaceFieldwithImage(document);
27+
28+
//Save the modified document
29+
using (FileStream outputStream1 = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
30+
{
31+
document.Save(outputStream1, FormatType.Docx);
32+
}
33+
//Create a DocIORenderer instance to convert the Word document to a PDF
34+
using (DocIORenderer render = new DocIORenderer())
35+
{
36+
//Convert the Word document to a PDF
37+
using (PdfDocument pdfDocument = render.ConvertToPDF(document))
38+
{
39+
//Save the generated PDF to a file
40+
using (FileStream outputStream1 = new FileStream(Path.GetFullPath(@"Output/Result.pdf"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
41+
{
42+
pdfDocument.Save(outputStream1);
43+
}
44+
}
45+
}
46+
}
47+
}
48+
}
49+
50+
/// <summary>
51+
/// Replaces fields with barcode images based on specific field codes in the document.
52+
/// </summary>
53+
/// <param name="document">The Word document object</param>
54+
private static void ReplaceFieldwithImage(WordDocument document)
55+
{
56+
// Find all fields in the document
57+
List<Entity> fields = document.FindAllItemsByProperty(EntityType.Field, "FieldType", "FieldUnknown");
58+
59+
// Iterate over all found fields
60+
foreach (WField field in fields)
61+
{
62+
if (field != null)
63+
{
64+
// Get the owner paragraph of the field
65+
WParagraph ownerParagraph = field.OwnerParagraph as WParagraph;
66+
// Get the index of the field within the paragraph
67+
int index = ownerParagraph.ChildEntities.IndexOf(field);
68+
// Split the field code to identify the type of barcode
69+
string[] components = field.FieldCode.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
70+
71+
// If the field is a QR code (check for "displaybarcode" and "qr")
72+
if (components[0].ToLower() == "displaybarcode" && components[2].ToLower() == "qr")
73+
{
74+
// Get the text to encode into the QR barcode
75+
string qrBarcodeText = components[1];
76+
77+
// Initialize default values for optional parameters
78+
int qValue = -1;
79+
float sValue = -1;
80+
float size = 90;
81+
82+
// Extract \q (error correction level) value
83+
var qMatch = Regex.Match(field.FieldCode, @"\\q (\d+)");
84+
if (qMatch.Success)
85+
{
86+
qValue = int.Parse(qMatch.Groups[1].Value);
87+
}
88+
89+
// Extract \s (size) value
90+
var sMatch = Regex.Match(field.FieldCode, @"\\s (\d+)");
91+
if (sMatch.Success)
92+
{
93+
sValue = int.Parse(sMatch.Groups[1].Value);
94+
size = sValue * 1.05f; // Scale the size slightly
95+
}
96+
97+
// Generate the QR barcode image as a byte array
98+
byte[] qrCode = GenerateQRBarcodeImage(qrBarcodeText, sValue, qValue, size);
99+
100+
// Create a new picture object to hold the barcode image
101+
WPicture picture = new WPicture(document);
102+
picture.LoadImage(qrCode);
103+
104+
// Replace the original field with the picture (QR code)
105+
ownerParagraph.ChildEntities.Remove(field);
106+
ownerParagraph.ChildEntities.Insert(index, picture);
107+
}
108+
// If the field is a Code39 barcode (check for "displaybarcode" and "code39")
109+
else if (components[0].ToLower() == "displaybarcode" && components[2].ToLower() == "code39")
110+
{
111+
// Get the text to encode into the Code39 barcode
112+
string qrBarcodeText = components[1];
113+
114+
// Initialize flags for optional parameters
115+
bool addText = false;
116+
117+
// Check for the \t option (whether to display text below the barcode)
118+
var tabMatch = Regex.IsMatch(field.FieldCode, @"\\t");
119+
if (tabMatch)
120+
{
121+
addText = true;
122+
}
123+
124+
125+
// Generate the Code39 barcode image as a byte array
126+
byte[] qrCode = GenerateCODE39Image(qrBarcodeText, addText);
127+
128+
// Create a new picture object to hold the barcode image
129+
WPicture picture = new WPicture(document);
130+
picture.LoadImage(qrCode);
131+
132+
// Replace the original field with the picture (Code39 barcode)
133+
ownerParagraph.ChildEntities.Remove(field);
134+
ownerParagraph.ChildEntities.Insert(index, picture);
135+
}
136+
}
137+
}
138+
}
139+
140+
/// <summary>
141+
/// Generates a QR barcode image and converts it to a byte array.
142+
/// </summary>
143+
/// <param name="qrBarcodeText">The text to be encoded in the QR code</param>
144+
/// <param name="sSwitchValue">The size value (\s option) for the QR code</param>
145+
/// <param name="qSwitchValue">The error correction level (\q option) for the QR code</param>
146+
/// <param name="size">The size of the QR code image</param>
147+
/// <returns>A byte array representing the QR code image</returns>
148+
private static byte[] GenerateQRBarcodeImage(string qrBarcodeText, float sSwitchValue, int qSwitchValue, float size)
149+
{
150+
// Create a new QR barcode instance
151+
PdfQRBarcode qrBarCode = new PdfQRBarcode();
152+
153+
// Set the text to be encoded
154+
qrBarCode.Text = qrBarcodeText;
155+
156+
// Set the size if provided
157+
if (sSwitchValue != -1)
158+
{
159+
qrBarCode.XDimension = sSwitchValue;
160+
}
161+
162+
// Set the error correction level based on the \q switch value
163+
if (qSwitchValue != -1)
164+
{
165+
switch (qSwitchValue)
166+
{
167+
case 0:
168+
qrBarCode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.Low;
169+
break;
170+
case 1:
171+
qrBarCode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.Medium;
172+
break;
173+
case 2:
174+
qrBarCode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.Quartile;
175+
break;
176+
case 3:
177+
qrBarCode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.High;
178+
break;
179+
}
180+
}
181+
182+
// Generate the QR code image and return it as a byte array
183+
Stream barcodeImage = qrBarCode.ToImage(new SizeF(size, size));
184+
byte[] byteArray;
185+
using (MemoryStream ms = new MemoryStream())
186+
{
187+
barcodeImage.CopyTo(ms);
188+
byteArray = ms.ToArray();
189+
}
190+
return byteArray;
191+
}
192+
193+
/// <summary>
194+
/// Generates a Code39 barcode image and converts it to a byte array.
195+
/// </summary>
196+
/// <param name="qrBarcodeText">The text to be encoded in the Code39 barcode</param>
197+
/// <param name="tSwitch">Whether to display the text below the barcode (\t option)</param>
198+
/// <returns>A byte array representing the Code39 barcode image</returns>
199+
private static byte[] GenerateCODE39Image(string qrBarcodeText, bool tSwitch)
200+
{
201+
// Create a new Code39 barcode instance
202+
PdfCode39Barcode barcode = new PdfCode39Barcode();
203+
204+
// Configure the barcode based on the provided options
205+
if (!tSwitch)
206+
{
207+
// If \t is not specified, don't display text
208+
barcode.Text = Regex.Replace(qrBarcodeText.ToUpper(), @"[^A-Z0-9\-\.\ \$\/\+\%]", "");
209+
barcode.TextDisplayLocation = TextLocation.None;
210+
}
211+
else
212+
{
213+
// If \t is specified, display the barcode text below the image
214+
barcode.Text = Regex.Replace(qrBarcodeText.ToUpper(), @"[^A-Z0-9\-\.\ \$\/\+\%]", "");
215+
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 15);
216+
barcode.Font = font;
217+
}
218+
219+
// Generate the barcode image and return it as a byte array
220+
Stream barcodeImage = barcode.ToImage(new SizeF(40, 40));
221+
byte[] byteArray;
222+
using (MemoryStream ms = new MemoryStream())
223+
{
224+
barcodeImage.CopyTo(ms);
225+
byteArray = ms.ToArray();
226+
}
227+
return byteArray;
228+
}
229+
}
230+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<RootNamespace>Replace_DISPLAYBARCODE_to_image</RootNamespace>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Syncfusion.DocIORenderer.Net.Core" Version="*" />
11+
<PackageReference Include="Syncfusion.Pdf.Imaging.Net.Core" Version="*" />
12+
</ItemGroup>
13+
14+
<ItemGroup>
15+
<None Update="Data\Template.docx">
16+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
17+
</None>
18+
<None Update="Output\.gitkeep">
19+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
20+
</None>
21+
</ItemGroup>
22+
23+
</Project>

0 commit comments

Comments
 (0)