チュートリアル
簡単にライブラリーを使用するためのチュートリアルコレクション
Word ドキュメントを TIFF に変換することは、さまざまなシナリオで役立ちます。TIFF ファイルは高品質で広くサポートされており、ドキュメントを共有するのに便利です。変換により Word ドキュメントが「フラット化」され、レイアウトが元のまま正確に保存されます。これにより、画像ベースのファイルが必要な他のアプリケーションやワークフローにドキュメントを組み込む際に役立ちます。
この記事では、C# と Spire.Doc for .NET ライブラリを使用して Word を TIFF に変換する方法を学びます。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET は、ドキュメント全体を画像の配列に変換するための Document.SaveToImages() メソッドを提供しています。その後、これらの個々の画像を組み合わせて単一の TIFF 画像にすることができます。
C# を使用して Word を TIFF に変換する手順は次のとおりです。
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Drawing.Imaging;
namespace WordToTiff
{
class Program
{
static void Main(string[] args)
{
// Documentオブジェクトを作成する
Document doc = new Document();
// Word文書を読み込む
doc.LoadFromFile("G:/Documents/Sample20.docx");
// 文書全体を画像に変換する
Image[] images = doc.SaveToImages(ImageType.Bitmap);
// 複数の画像をTIFFファイルに変換する
ConvertImagesToTiff(images, "WordをTiffに変換.tiff", EncoderValue.CompressionLZW);
// リソースを解放する
doc.Dispose();
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// 画像エンコーダを取得する
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; j++)
{
// 指定されたMIMEタイプに一致するエンコーダを見つける
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
}
public static void ConvertImagesToTiff(Image[] images, string outFile, EncoderValue compressEncoder)
{
// エンコーダパラメータを設定する
Encoder enc = Encoder.SaveFlag;
EncoderParameters ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
// 最初の画像を取得する
Image pages = images[0];
// 変数を作成する
int frame = 0;
// TIFF画像コーデック情報を処理するためのImageCodecInfoオブジェクトを取得する
ImageCodecInfo info = GetEncoderInfo("image/tiff");
// 各画像を反復処理する
foreach (Image img in images)
{
// 最初のフレームの場合、指定されたエンコーダパラメータで出力ファイルに保存する
if (frame == 0)
{
pages = img;
pages.Save(outFile, info, ep);
}
else
{
// 中間フレームを保存する
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
pages.SaveAdd(img, ep);
}
// 最後のフレームの場合、エンコーダパラメータをフラッシュし、ファイルを閉じる
if (frame == images.Length - 1)
{
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
pages.SaveAdd(ep);
}
frame++;
}
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
テキストファイルはシンプルで汎用性がありますが、フォーマットオプションやヘッダー、フッター、ページ番号、スタイルなどの高度な機能をサポートしていません。また、画像や表などのマルチメディアコンテンツも含めることができません。さらに、プレーンテキストエディタではスペルチェックや文法チェック機能も利用できません。
テキストドキュメントにフォーマット、マルチメディアコンテンツ、または高度な機能を追加する必要がある場合は、より高度なフォーマットである Word に変換する必要があります。同様に、Word ドキュメントのフォーマットを簡素化したり、ファイルサイズを削減したり、その内容を基本的なツールで操作する必要がある場合は、プレーンテキストフォーマットに変換する必要があります。本記事では、Spire.Doc for .NET ライブラリを使用して、C# でテキストファイルを Word ドキュメントに変換する方法と、Word ドキュメントをテキスト形式に変換する方法を説明します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET は、Document.LoadText(string fileName) メソッドを提供しており、このメソッドを使用してテキストファイルを読み込むことができます。テキストファイルが読み込まれた後、Document.SaveToFile(string fileName, FileFormat fileFormat) メソッドを使用して簡単に Word 形式で保存できます。詳細な手順は以下の通りです:
using Spire.Doc;
using Spire.Doc.Documents;
namespace TextToWord
{
class Program
{
static void Main(string[] args)
{
// Documentクラスのインスタンスを作成
Document doc = new Document();
// テキストファイルを読み込む
doc.LoadFromFile("Sample.txt");
// 変換結果を向上させるための基本的なフォント設定を行う(オプション)
// スタイルを作成
ParagraphStyle style = new ParagraphStyle(doc);
// フォント名とフォントサイズを設定
style.CharacterFormat.FontName = "Yu Mincho";
style.CharacterFormat.FontSize = 12;
doc.Styles.Add(style);
// すべての段落にスタイルを適用
Section section = doc.Sections[0];
foreach (Paragraph paragraph in section.Paragraphs)
{
paragraph.ApplyStyle(style);
}
// テキストファイルをWord文書として保存
doc.SaveToFile("テキストをWordに変換.docx");
doc.Dispose();
}
}
}
Word ファイルをテキスト形式に変換するには、まず Document.LoadFromFile(string fileName) メソッドを使用して Word ファイルを読み込み、その後、Document.SaveToFile(string fileName, FileFormat fileFormat) メソッドを呼び出してテキスト形式で保存するだけです。詳細な手順は以下の通りです:
using Spire.Doc;
using Spire.Doc.Documents;
namespace TextToWord
{
class Program
{
static void Main(string[] args)
{
// Documentクラスのインスタンスを作成
Document doc = new Document();
// Word文書を読み込む
doc.LoadFromFile("Sample.docx");
// Word文書をテキストファイルとして保存
doc.SaveToFile("Wordをテキストに変換.txt", FileFormat.Txt);
doc.Dispose();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Markdown は、軽量なマークアップ言語として、プログラマーや技術文書の執筆者によってそのシンプルさ、読みやすさ、明確な構文のために好まれています。しかし、特定のシナリオでは、Markdown ドキュメントを豊富な書式設定機能とレイアウトの制御を持つ Word ドキュメントに変換したり、印刷や簡単な閲覧に適した PDF ファイルを Markdown ドキュメントから生成する必要がしばしばあります。この記事では、異なるシナリオでのさまざまな文書処理の要件を満たすために、Spire.Doc for .NET を使用して Markdown ファイルを Word ドキュメントまたは PDF ファイルに変換する方法を説明します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET を使用すると、Document.LoadFromFile(string fileName, FileFormat.Markdown) メソッドを使用して Markdown ファイルを読み込み、Document.SaveToFile(string fileName, fileFormat FileFormat) メソッドを使用してそのファイルを他の形式に変換できます。
Markdown ファイル内の画像はリンクとして保存されるため、Markdown ファイルを Word ドキュメントに直接変換するのは、画像を含まない Markdown ファイルに適しています。ファイルに画像が含まれている場合は、変換後に画像のさらなる処理が必要です。
以下は、Markdown ファイルを Word ドキュメントに変換する手順です:
using Spire.Doc;
namespace MdToDocx
{
class Program
{
static void Main(string[] args)
{
// Documentクラスのオブジェクトを作成する
Document doc = new Document();
// Markdownファイルを読み込む
doc.LoadFromFile("サンプル.md", FileFormat.Markdown);
// MarkdownファイルをWord文書に変換する
doc.SaveToFile("MarkdownToWord.docx", FileFormat.Docx);
doc.Close();
}
}
}
また、FileFormat.PDF Enum をパラメータとして使用することで、Markdown ファイルを直接 PDF ファイルに変換することもできます。以下は Markdown ファイルを PDF ファイルに変換する手順です:
using Spire.Doc;
namespace MdToDocx
{
class Program
{
static void Main(string[] args)
{
// Documentクラスのオブジェクトを作成する
Document doc = new Document();
// Markdownファイルを読み込む
doc.LoadFromFile("サンプル.md", FileFormat.Markdown);
// MarkdownファイルをPDFファイルに変換する
doc.SaveToFile("MarkdownToPDF.pdf", FileFormat.PDF);
doc.Close();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
PDF は Word 文書に比べて多くの利点があります。例えば、PDF にはレイアウトが固定されているため、さまざまなデバイスやオペレーティングシステムで文書を表示する際に、フォーマットや内容が変わらないことが保証されます。そのため、文書を共有したり転送したりする際には、Word 文書を PDF に変換することをお勧めします。この記事では、Spire.Doc for .NET を使用して、C# および VB.NET でプログラムによって Word を PDF に変換する方法を示します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET が提供する Document.SaveToFile(string fileName, FileFormat fileFormat) メソッドは、Word を PDF、XPS、HTML、RTF などとして保存することができます。Word 文書を一般的な PDF として保存するだけで、他の設定を必要としない場合は、次の手順に従います。
using Spire.Doc;
namespace ToPDF
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document document = new Document();
//Word文書をロードする
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//文書をPDFとして保存する
document.SaveToFile("ToPDF.pdf", FileFormat.PDF);
}
}
}
Imports Spire.Doc
Namespace ToPDF
Class Program
Private Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim document As Document = New Document
'Word文書をロードする
document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")
'文書をPDFとして保存する
document.SaveToFile("ToPDF.pdf", FileFormat.PDF)
End Sub
End Class
End Namespace
Word をパスワードで保護された PDF に変換するには、Document.SaveToFile(string fileName, ToPdfParameterList paramList) メソッドを使用できます。ToPdfParameterList パラメーターは、Word 文書が PDF に変換される方法を制御します。たとえば、変換中に文書を暗号化するかどうかなどがあります。詳細な手順は次のとおりです。
using Spire.Doc;
namespace ToPDFWithPassword
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document document = new Document();
//Word文書をロードする
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//ToPdfParameterListインスタンスを作成する
ToPdfParameterList parameters = new ToPdfParameterList();
//PDFの開くためのパスワードと権限のパスワードを設定する
string openPsd = "E-iceblue";
string permissionPsd = "abc123";
parameters.PdfSecurity.Encrypt(openPsd, permissionPsd, Spire.Pdf.Security.PdfPermissionsFlags.Default, Spire.Pdf.Security.PdfEncryptionKeySize.Key128Bit);
//Wordをパスワードで保護されたPDFとして保存する
document.SaveToFile("ToPDFWithPassword.pdf", parameters);
}
}
}
Imports Spire.Doc
Namespace ToPDFWithPassword
Class Program
Private Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim document As Document = New Document
'Word文書をロードする
document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")
'ToPdfParameterListインスタンスを作成する
Dim parameters As ToPdfParameterList = New ToPdfParameterList
'PDFの開くためのパスワードと権限のパスワードを設定する
Dim openPsd As String = "E-iceblue"
Dim permissionPsd As String = "abc123"
parameters.PdfSecurity.Encrypt(openPsd, permissionPsd, Spire.Pdf.Security.PdfPermissionsFlags.Default, Spire.Pdf.Security.PdfEncryptionKeySize.Key128Bit)
'Wordをパスワードで保護されたPDFとして保存する
document.SaveToFile("ToPDFWithPassword.pdf", parameters)
End Sub
End Class
End Namespace
ブックマークは文書の読みやすさを向上させることができます。Word を PDF に変換する場合、既存の Word 文書のブックマークを保持するか、見出しに基づいてブックマークを作成できます。以下は詳細な手順です。
using Spire.Doc;
namespace ToPDFWithBookmarks
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document document = new Document();
//Word文書をロードする
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//ToPdfParameterListオブジェクトを作成する
ToPdfParameterList parameters = new ToPdfParameterList();
//Wordのブックマークに基づいてPDFにブックマークを作成する
parameters.CreateWordBookmarks = true;
//Wordの見出しに基づいてPDFにブックマークを作成する
//parameters.CreateWordBookmarksUsingHeadings= true;
//文書をPDFとして保存する
document.SaveToFile("ToPDFWithBookmarks.pdf", parameters);
}
}
}
Imports Spire.Doc
Namespace ToPDFWithBookmarks
Class Program
Private Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim document As Document = New Document
'Word文書をロードする
document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")
'ToPdfParameterListオブジェクトを作成する
Dim parameters As ToPdfParameterList = New ToPdfParameterList
'Wordのブックマークに基づいてPDFにブックマークを作成する
parameters.CreateWordBookmarks = True
'Wordの見出しに基づいてPDFにブックマークを作成する
'parameters.CreateWordBookmarksUsingHeadings= true;
'文書をPDFとして保存する
document.SaveToFile("ToPDFWithBookmarks.pdf", parameters)
End Sub
End Class
End Namespace
Word 文書で使用されているフォントを PDF 文書に埋め込むことで、PDF 文書が適切なフォントがインストールされていない任意のデバイスで同じように見えるようにすることができます。以下は詳細な手順です。
using Spire.Doc;
namespace ToPDFWithFontsEmbedded
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document document = new Document();
//Word文書をロードする
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//ToPdfParameterListオブジェクトを作成する
ToPdfParameterList parameters = new ToPdfParameterList();
//生成されたPDFに特定のフォントを埋め込む
parameters.IsEmbeddedAllFonts = true;
//文書をPDFとして保存する
document.SaveToFile("ToPDFWithFontsEmbedded.pdf", parameters);
}
}
}
Imports Spire.Doc
Namespace ToPDFWithFontsEmbedded
Class Program
Private Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim document As Document = New Document
'Word文書をロードする
document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")
'ToPdfParameterListオブジェクトを作成する
Dim parameters As ToPdfParameterList = New ToPdfParameterList
'生成されたPDFに特定のフォントを埋め込む
parameters.IsEmbeddedAllFonts = True
'文書をPDFとして保存する
document.SaveToFile("ToPDFWithFontsEmbedded.pdf", parameters)
End Sub
End Class
End Namespace
高品質の画像が多く含まれる文書のサイズは、通常は大きくなります。Word を PDF に変換する際に、画像の品質を圧縮するかどうかを決定できます。以下は詳細な手順です。
using Spire.Doc;
namespace SetImageQuality
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document document = new Document();
//Word文書をロードする
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//画像を原図画質の40%に圧縮する
document.JPEGQuality = 40;
//原図画質を維持する
//document.JPEGQuality = 100;
//文書をPDFとして保存する
document.SaveToFile("SetImageQuantity.pdf", FileFormat.PDF);
}
}
}
Imports Spire.Doc
Namespace SetImageQuality
Class Program
Private Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim document As Document = New Document
'Word文書をロードする
document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")
'画像を原図画質の40%に圧縮する
document.JPEGQuality = 40
'原図画質を維持する
'document.JPEGQuality = 100;
'文書をPDFとして保存する
document.SaveToFile("SetImageQuantity.pdf", FileFormat.PDF)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word と Excel は全く異なるファイルタイプです。Word ドキュメントは、論文、手紙、またはレポートを書くために使用されます。Excel ドキュメントは、データを表形式で保存したり、グラフを作成したり、データを計算したりするために使用されます。通常、Excel は Word の元のレイアウトを表示するのが難しいため、複雑な Word ドキュメントを Excel スプレッドシートに変換することはお勧めしません。
ただし、Word ドキュメントが主に表から構成されており、Excel で表データを分析したい場合は、Spire.Office for .NET を使用して Word を Excel に変換できます。この方法により、ドキュメントの可読性を維持することもできます。
まず、Spire.Office for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
bPM> Install-Package Spire.Office
このシーンでは、実際に Spire.Office パッケージの2つのライブラリが使用されています。Spire.Doc for .NET は、Word ドキュメントからコンテンツを読み取り、抽出するために使用されます。Spire.XLS for .NET は、Excel ドキュメントを作成し、特定のセルにデータを書き込むために使用されます。このコード例を理解しやすくするために、次の3つのカスタム方法を作成して変換機能を実現しました。
次の手順では、Spire.Office for .NET を使用して Word ドキュメント全体からワークシートにデータをエクスポートする方法を示します。
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document doc = new Document();
//Wordサンプル・ドキュメントをロードする
doc.LoadFromFile(@"sample.docx");
//Workbookオブジェクトを作成する
Workbook wb = new Workbook();
//デフォルト・ワークシートを削除する
wb.Worksheets.Clear();
//「WordToExcel」というワークシートを作成する
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Wordドキュメントのセクションをループする
foreach (Section section in doc.Sections)
{
//セクション内のドキュメントオブジェクトをループする
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//オブジェクトが段落かどうかを判断する
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Wordの段落を特定のセルにコピーする
CopyTextAndStyle(cell, paragraph);
row++;
}
//オブジェクトがテーブルかどうかを判断する
if (documentObject is Table)
{
Table table = documentObject as Table;
//テーブルのデータをWordからExcelにエクスポートする
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//行の高さと列の幅を自動調整する
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//テキストをセルでラップする
worksheet.AllocatedRange.IsWrapText = true;
//ワークブックをExcelに保存する
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//WordのテーブルからExcelセルにデータをエクスポートする
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//WordテーブルのセルからExcelのセルにコンテンツをコピーする
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//段落のテキストとスタイルをセルにコピーする
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Xls
Imports System
Imports System.Drawing
Namespace ConvertWordToExcel
Class Program
Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Document doc = New Document()
'Wordサンプル・ドキュメントをロードする
doc.LoadFromFile("sample.docx")
'Workbookオブジェクトを作成する
Dim wb As Workbook = New Workbook()
'デフォルト・ワークシートを削除する
wb.Worksheets.Clear()
'「WordToExcel」というワークシートを作成する
Dim worksheet As Worksheet = wb.CreateEmptySheet("WordToExcel")
Dim row As Integer = 1
Dim column As Integer = 1
'Wordドキュメントのセクションをループする
Dim section As Section
For Each section In doc.Sections
'セクション内のドキュメントオブジェクトをループする
Dim documentObject As DocumentObject
For Each documentObject In section.Body.ChildObjects
'オブジェクトが段落かどうかを判断する
If TypeOf documentObject Is Paragraph Then
Dim cell As CellRange = worksheet.Range(row,column)
Dim paragraph As Paragraph = documentObject as Paragraph
'Wordの段落を特定のセルにコピーする
CopyTextAndStyle(cell, paragraph)
row = row + 1
End If
'オブジェクトがテーブルかどうかを判断する
If TypeOf documentObject Is Table Then
Dim table As Table = documentObject as Table
'テーブルのデータをWordからExcelにエクスポートする
Dim currentRow As Integer = ExportTableInExcel(worksheet,row,table)
row = currentRow
End If
Next
Next
'行の高さと列の幅を自動調整する
worksheet.AllocatedRange.AutoFitRows()
worksheet.AllocatedRange.AutoFitColumns()
'テキストをセルでラップする
worksheet.AllocatedRange.IsWrapText = True
'ワークブックをExcelに保存する
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013)
End Sub
'WordのテーブルからExcelセルにデータをエクスポートする
Private Shared Function ExportTableInExcel(ByVal worksheet As Worksheet, ByVal row As Integer, ByVal table As Table) As Integer
Dim cell As CellRange
Dim column As Integer
Dim tbRow As TableRow
For Each tbRow In table.Rows
column = 1
Dim tbCell As TableCell
For Each tbCell In tbRow.Cells
cell = worksheet.Range(row, column)
cell.BorderAround(LineStyleType.Thin, Color.Black)
CopyContentInTable(tbCell, cell)
column = column + 1
Next
row = row + 1
Next
Return row
End Function
'WordテーブルのセルからExcelのセルにコンテンツをコピーする
Private Shared Sub CopyContentInTable(ByVal tbCell As TableCell, ByVal cell As CellRange)
Dim NewPara As Paragraph = New Paragraph(tbCell.Document)
Dim i As Integer
For i = 0 To tbCell.ChildObjects.Count- 1 Step i + 1
Dim documentObject As DocumentObject = tbCell.ChildObjects(i)
If TypeOf documentObject Is Paragraph Then
Dim paragraph As Paragraph = documentObject as Paragraph
Dim cObj As DocumentObject
For Each cObj In paragraph.ChildObjects
NewPara.ChildObjects.Add(cObj.Clone())
Next
If i < tbCell.ChildObjects.Count - 1 Then
NewPara.AppendText("\n")
End If
End If
Next
CopyTextAndStyle(cell, NewPara)
End Sub
'段落のテキストとスタイルをセルにコピーする
Private Shared Sub CopyTextAndStyle(ByVal cell As CellRange, ByVal paragraph As Paragraph)
Dim richText As RichText = cell.RichText
richText.Text = paragraph.Text
Dim startIndex As Integer = 0
Dim documentObject As DocumentObject
For Each documentObject In paragraph.ChildObjects
If TypeOf documentObject Is TextRange Then
Dim textRange As TextRange = documentObject as TextRange
Dim fontName As String = textRange.CharacterFormat.FontName
Dim isBold As Boolean = textRange.CharacterFormat.Bold
Dim textColor As Color = textRange.CharacterFormat.TextColor
Dim fontSize As single = textRange.CharacterFormat.FontSize
Dim textRangeText As String = textRange.Text
Dim strLength As Integer = textRangeText.Length
Dim font As ExcelFont = cell.Worksheet.Workbook.CreateFont()
font.Color = textColor
font.IsBold = isBold
font.Size = fontSize
font.FontName = fontName
Dim endIndex As Integer = startIndex + strLength
richText.SetFont(startIndex, endIndex, font)
startIndex += strLength
End If
If TypeOf documentObject Is DocPicture Then
Dim picture As DocPicture = documentObject as DocPicture
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image)
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height)
End If
Next
Select Case paragraph.Format.HorizontalAlignment
Case HorizontalAlignment.Left
cell.Style.HorizontalAlignment = HorizontalAlignType.Left
Exit For
Case HorizontalAlignment.Center
cell.Style.HorizontalAlignment = HorizontalAlignType.Center
Exit For
Case HorizontalAlignment.Right
cell.Style.HorizontalAlignment = HorizontalAlignType.Right
Exit For
End Select
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
コンピュータに MS Word をインストールする必要がないため、Word 文書形式よりも、イメージ書式をプラットフォーム間で共有したりプレビューしたりするのが便利です。また、Word をイメージに変換することで、文書のオリジナルの外観を維持でき、他の人がそれをさらに修正するのを防ぐことができます。この記事では、Spire.Doc for .NET を使用して、C# および VB.NET でプログラムによって Word をイメージに変換する方法を示します。
まず、Spire.Doc for.NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET が提供する Document.SaveToImages() メソッドは、Word 文書のページを Bitmap または Metafile に変換します。その後、Bitmap または Metafile は、BMP、EMF、JPEG、PNG、GIF または WMF 書式のイメージとして保存することができます。以下は Word を JPG に変換するための詳細な手順です。
using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertWordToJPG
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document doc = new Document();
//Wordをロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
//文書全体のページをイメージに変換する
Image[] images = doc.SaveToImages(ImageType.Bitmap);
//イメージコレクションをループする
for (int i = 0; i < images.Length; i++)
{
//イメージをJPGとして保存する
string outputfile = String.Format("Image-{0}.jpg", i);
images[i].Save("C:\\Users\\Administrator\\Desktop\\Images\\" + outputfile, ImageFormat.Jpeg);
}
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Namespace ConvertWordToJPG
Class Program
Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Document doc = New Document()
'Wordをロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx")
'文書全体のページをイメージに変換する
Dim images() As Image = doc.SaveToImages(ImageType.Bitmap)
'イメージコレクションをループする
Dim i As Integer
For i = 0 To images.Length- 1 Step i + 1
'イメージをJPGとして保存する
Dim outputfile As String = String.Format("Image-{0}.jpg",i)
images(i).Save("C:\\Users\\Administrator\\Desktop\\Images\\" + outputfile, ImageFormat.Jpeg)
Next
End Sub
End Class
End Namespace
Spire.Doc for .NET を使用して Word 文書を一連のバイト配列として保存し、SVG 文書にそれぞれ書き込むことができます。Word を SVG に変換するための詳細な手順は次のとおりです。
using Spire.Doc;
using System;
using System.Collections.Generic;
using System.IO;
namespace CovnertWordToSVG
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document doc = new Document();
//Wordをロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
//文書をバイト配列キューとして保存する
Queue<byte[]> svgBytes = doc.SaveToSVG();
//すべてのバイト配列をループする
for (int i = 0; i < svgBytes.Count; i++)
{
//キューを配列に変換する
byte[][] bytes = svgBytes.ToArray();
//出力文書名を指定する
string outputfile = String.Format("Image-{0}.svg", i);
//SVG文書にバイト配列を書き込む
FileStream fs = new FileStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputfile, FileMode.Create);
fs.Write(bytes[i], 0, bytes[i].Length);
fs.Close();
}
}
}
}
Imports Spire.Doc
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace CovnertWordToSVG
Class Program
Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Document doc = New Document()
'Wordをロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx")
'文書をバイト配列キューとして保存する
Dim svgBytes()> As Queue<byte = doc.SaveToSVG()
'すべてのバイト配列をループする
Dim i As Integer
For i = 0 To svgBytes.Count- 1 Step i + 1
'キューを配列に変換する
Dim bytes()() As Byte = svgBytes.ToArray()
'出力文書名を指定する
Dim outputfile As String = String.Format("Image-{0}.svg",i)
' SVG文書にバイト配列を書き込む
Dim fs As FileStream = New FileStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputfile,FileMode.Create)
fs.Write(bytes(i), 0, bytes(i).Length)
fs.Close()
Next
End Sub
End Class
End Namespace
より解像度の高いイメージはコンテンツをより明確に表示することができます。以下の手順に従って、Word を PNG に変換するときに、イメージ解像度を設定することができます。
using Spire.Doc;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using Spire.Doc.Documents;
namespace ConvertWordToPng
{
class Program
{
static void Main(string[] args)
{
//Documentオブジェクトを作成する
Document doc = new Document();
//Word文書をロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx ");
//文書全体のページをイメージに変換する
Image[] images = doc.SaveToImages(ImageType.Metafile);
//イメージコレクションをループする
for (int i = 0; i < images.Length; i++)
{
//イメージの解像度を設定する
Image newimage = ResetResolution(images[i] as Metafile, 150);
//イメージをPNGとして保存する
string outputfile = String.Format("image-{0}.png", i);
newimage.Save(outputfile, ImageFormat.Png);
}
}
//ResetResolution()を使用しでイメージの解像度を設定する
public static Image ResetResolution(Metafile mf, float resolution)
{
int width = (int)(mf.Width * resolution / mf.HorizontalResolution);
int height = (int)(mf.Height * resolution / mf.VerticalResolution);
Bitmap bmp = new Bitmap(width, height);
bmp.SetResolution(resolution, resolution);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(mf, Point.Empty);
}
return bmp;
}
}
}
Imports Spire.Doc
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports Spire.Doc.Documents
Namespace ConvertWordToPng
Class Program
Shared Sub Main(ByVal args() As String)
'Documentオブジェクトを作成する
Dim doc As Document = New Document()
'Word文書をロードする
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx")
'文書全体のページをイメージに変換する
Dim images() As Image = doc.SaveToImages(ImageType.Metafile)
'イメージコレクションをループする
Dim i As Integer
For i = 0 To images.Length - 1 Step i + 1
'イメージの解像度を設定する
Dim Newimage As Image = ResetResolution(images(i) As Metafile, 150)
'イメージをPNGとして保存する
Dim outputfile As String = String.Format("image-{0}.png", i)
Newimage.Save(outputfile, ImageFormat.Png)
Next
End Sub
'ResetResolution()を使用しでイメージの解像度を設定する
Public Shared Function ResetResolution(ByVal mf As Metafile, ByVal resolution As Single) As Image
Dim width As Integer = CType((mf.Width * resolution / mf.HorizontalResolution), Integer)
Dim height As Integer = CType((mf.Height * resolution / mf.VerticalResolution), Integer)
Dim bmp As Bitmap = New Bitmap(width, height)
bmp.SetResolution(resolution, resolution)
Imports (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(mf, PoInteger.Empty)
}
Return bmp
End Function
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
XPS (XML Paper Specification) は、固定レイアウトのドキュメント書式です。この書式は、ドキュメントの忠実度を維持し、デバイスに依存しないドキュメントの外観を提供します。XPS は PDF に似ていますが、XPS は PostScript ではなく XML に基づいています。Word を固定レイアウトのドキュメント書式として保存するには、XPS が良い選択です。この記事では、Spire.Doc for .NET を使用して、C# および VB.NET で Word を XPS に変換する方法を示します。
まず、Spire.Doc for.NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc for .NET を使用して Word を XPS に変換するには、Word ドキュメントをロードして XPS ドキュメント書式として保存するだけです。詳細な手順は次のとおりです。
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Documentクラスのオブジェクトを作成する
Document doc = new Document();
//Wordドキュメントをロードする
doc.LoadFromFile(@"sample.docx");
//WordをXPSとして保存する
doc.SaveToFile("Word to XPS.xps", FileFormat.XPS);
}
}
}
Imports Spire.Doc
Namespace ConvertWordToXps
Class Program
Shared Sub Main(ByVal args() As String)
'Documentクラスのオブジェクトを作成する
Dim doc As Document = New Document()
'Wordドキュメントをロードする
doc.LoadFromFile("sample.docx")
'WordをXPSとして保存する
doc.SaveToFile("Word to XPS.xps", FileFormat.XPS)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
XML はテキストマークアップ言語であり、主に任意のデータを保存して転送するために使用されます。XML ファイルは簡潔、普遍的、使いやすいなどの特徴があり、ネットワークサーバの中で特に人気があります。XML と HTML はいずれもテキストマークアップ言語であり、類似性があるが、両者の応用シーンは異なります。XML は主にデータの保存と転送に使用されるが、HTML は Web ページのコンテンツを表示するために使用される。この記事では、Spire.Doc for .NET を使用して、C# および VB.NET でプログラムによって Word を XML に変換する方法を示します。
まず、Spire.Doc for.NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
次の手順は、Spire.Doc for .NET を使用して Word を XML に変換する方法を示しています。
using System;
using Spire.Doc;
namespace WordtoXML
{
internal class Program
{
static void Main(string[] args)
{
// Documentクラスのオブジェクトを作成する
Document document = new Document();
// Wordドキュメントをディスクからロードする
document.LoadFromFile(@"Sample.docx");
// WordドキュメントをXMLファイルとして保存する
document.SaveToFile("Sample to xml.xml", FileFormat.Xml);
}
}
}
Imports System
Imports Spire.Doc
Module Program
Sub Main(args As String())
' Documentクラスのオブジェクトを作成する
Dim document As New Document()
' Wordドキュメントをディスクからロードする
document.LoadFromFile("Sample.docx")
' WordドキュメントをXMLファイルとして保存する
document.SaveToFile("Sample to xml.xml", FileFormat.Xml)
End Sub
End Module
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word 文書を Web に掲載する場合は、Web ページからアクセスできるようにするために文書を HTML に変換することをお勧めします。この記事では、Spire.Doc for .NET を使用して、C# および VB.NET でプログラムによって Word を HTML に変換する方法を示します。
まず、Spire.Doc for.NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
次の手順は、Spire.Doc for .NET を使用して Word を HTML に変換する方法を示しています。
using Spire.Doc;
namespace WordToHTML
{
class Program
{
static void Main(string[] args)
{
//ドキュメントインスタンスを作成する
Document mydoc = new Document();
//Wordサンプルドキュメントを読み込む
mydoc.LoadFromFile(@"sample.docx", FileFormat.Xml);
//HTMLに保存する
mydoc.SaveToFile("output_WordToHTML.html", FileFormat.Html);
}
}
}
Imports Spire.Doc
Namespace WordToHTML
Class Program
Shared Sub Main(ByVal args() As String)
'ドキュメントインスタンスを作成する
Document mydoc = New Document()
'Wordサンプルドキュメントを読み込む
mydoc.LoadFromFile("sample.docx", FileFormat.Xml)
'HTMLに保存する
mydoc.SaveToFile("output_WordToHTML.html", FileFormat.Html)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。