You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

849 lines
36 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/************************************************************************************
* Copyright (c) 2018 All Rights Reserved.
* CLR版本 4.0.30319.36399
*机器名称HUBING
*公司名称:杭州康勒科技有限公司
*命名空间HelloTeamcenter.hello
*文件名: PrintDwg
*版本号: V1.0.0.0
*唯一标识0679f0a0-c63f-454a-8a8f-b7db7cb9cfc6
*当前的用户域HUBING
*创建人: hub
*电子邮箱hub@connor.net.cn
*创建时间2018/5/28 16:26:39
*描述:
*
*=====================================================================
*修改标记
*修改时间2018/5/28 16:26:39
*修改人: hub
*版本号: V1.0.0.0
*描述:
*
/************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//*******************************************//
// Type Library //
//*******************************************//
//using ZwSoft.ZwCAD.Customization; //accui.dll
//*******************************************//
// acdbmgd.dll //
//*******************************************//
using ZwSoft.ZwCAD.Runtime;
using ZwSoft.ZwCAD.LayerManager;
using ZwSoft.ZwCAD.GraphicsSystem;
using ZwSoft.ZwCAD.GraphicsInterface;
using ZwSoft.ZwCAD.Geometry;
using ZwSoft.ZwCAD.DatabaseServices.Filters;
using ZwSoft.ZwCAD.DatabaseServices;
using ZwSoft.ZwCAD.Colors;
//******************************************//
//--------------------------------------------//
// acmgd.dll //
//------------------------------------------*//
//using ZwSoft.ZwCAD.Windows.ToolPalette;
using ZwSoft.ZwCAD.Windows;
using ZwSoft.ZwCAD.Publishing;
using ZwSoft.ZwCAD.PlottingServices;
using ZwSoft.ZwCAD.EditorInput;
using ZwSoft.ZwCAD.ApplicationServices;
using AcAp = ZwSoft.ZwCAD.ApplicationServices.Application;
using DataSvr = ZwSoft.ZwCAD.DatabaseServices;
using System.Collections;
using System.Threading;
using System.Collections.Specialized;
using HelloTeamcenter.hello;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text;
namespace KCad
{
public class FrameCompare : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare(Object x, Object y)
{
if (string.Compare((x as PrintFrame).BKName, (y as PrintFrame).BKName, true) == 0)
{
return 0;
}
return -1;
}
}
public class PrintFrame
{
public string BKName
{
get;
set;
}
public string MediaName
{
get;
set;
}
public Extents2d PrintBound
{
get;
set;
}
public DataSvr.PlotRotation Rotation
{
get;
set;
}
public void Clone(PrintFrame obj)
{
BKName = obj.BKName;
MediaName = obj.MediaName;
PrintBound = obj.PrintBound;
Rotation = obj.Rotation;
BlockF = obj.BlockF;
}
public string BlockF
{
get;
set;
}
public double _X
{
get;
set;
}
public double _Y
{
get;
set;
}
}
public class PrintDwg
{
private ArrayList m_Frame = null;
private string CAD_BLOCK_SIZE_MAPPING = "CN_cad_block_size_mapping";
public PrintDwg(ZwSoft.ZwCAD.ApplicationServices.Document doc)
{
m_Frame = new ArrayList();
// m_Frame.Add(new PrintFrame() { BKName = "KHGY-TH", MediaName = "ISO_expand_A4_(297.00_x_210.00_MM)", Rotation = DataSvr.PlotRotation.Degrees000 });
// m_Frame.Add(new PrintFrame() { BKName = "KHGY-TK", MediaName = "ISO_expand_A4_(297.00_x_210.00_MM)", Rotation = DataSvr.PlotRotation.Degrees000 });
// m_Frame.Add(new PrintFrame() { BKName = "KHTH-H", MediaName = "ISO_expand_A4_(297.00_x_210.00_MM)", Rotation = DataSvr.PlotRotation.Degrees000 });
// m_Frame.Add(new PrintFrame() { BKName = "KHTH-H-A3", MediaName = "ISO_expand_A3_(420.00_x_297.00_MM)", Rotation = DataSvr.PlotRotation.Degrees000 });
// m_Frame.Add(new PrintFrame() { BKName = "KHTH-Z", MediaName = "ISO_expand_A4_(297.00_x_210.00_MM)", Rotation = DataSvr.PlotRotation.Degrees090 });
// m_Frame.Add(new PrintFrame() { BKName = "KHTH-Z-A3", MediaName = "ISO_expand_A3_(420.00_x_297.00_MM)", Rotation = DataSvr.PlotRotation.Degrees090 });
// m_Frame.Add(new PrintFrame() { BKName = "a3n", MediaName = "ISO_expand_A3_(420.00_x_297.00_MM)", Rotation = DataSvr.PlotRotation.Degrees090 });
Editor ed1 = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
try
{
Tool tool = new Tool();
Hashtable pre = tool.getTCPreferences(CAD_BLOCK_SIZE_MAPPING);
string[] prevalues = (string[])pre[CAD_BLOCK_SIZE_MAPPING];
//string[] prevalues = new String[] { "A0-H=A0=841.00_x_1189.00=W", "A1-H=A1=841.00_x_594.00=W","A2-H=A2=594.00_x_420.00=W", "A4-S=A4=297.00_x_210.00=H" };//{ "A0-H=A0=841.00_x_1189.00=W"};
if (prevalues != null && prevalues.Length > 0)
{
foreach (string value in prevalues)
{
ed1.WriteMessage("REF=>" + value+"\n");
string[] values = value.Split("=".ToCharArray());
if (values.Length == 4)
{ //a3n=A3=420.00_x_297.00
if (values[3].Equals("W"))
{
ed1.WriteMessage("REF=90=>\n");
m_Frame.Add(new PrintFrame() { BKName = values[0], MediaName = String.Format("ISO_expand_{0}_({1}_MM)", values[1], values[2]), Rotation = DataSvr.PlotRotation.Degrees090, BlockF = values[3] });
}else{
ed1.WriteMessage("REF=00=>\n");
m_Frame.Add(new PrintFrame() { BKName = values[0], MediaName = String.Format("ISO_expand_{0}_({1}_MM)", values[1], values[2]), Rotation = DataSvr.PlotRotation.Degrees090, BlockF = values[3] });
}
}
}
}
}catch(System.Exception e){
ed1.WriteMessage(e.StackTrace);
}
PrintDoc = doc;
}
/// <summary>
/// PDF旋转90度
/// </summary>
/// <returns></returns>
public string PdfTo90(string inputfilepath, PrintFrame frame)
{
string pdfNewPath =null;
if (frame.BlockF.Equals("W"))
{
pdfNewPath = inputfilepath.Replace("DWG_PDF", "DWG_PDF_M");
}else{
pdfNewPath = inputfilepath.Replace("DWG_PDF", "DWG_PDF_M");
//pdfNewPath = inputfilepath;
//return pdfNewPath;
}
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
try
{
pdfReader = new PdfReader(inputfilepath);
pdfStamper = new PdfStamper(pdfReader, new FileStream(pdfNewPath, FileMode.Create));
int numberOfPages = pdfReader.NumberOfPages;
for (int i = 1; i <= numberOfPages; i++)
{
//转换角度
if (frame.BlockF.Equals("W"))
{
PdfDictionary page = pdfReader.GetPageN(i);
PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
int rotation = rotate == null ? 90 : (rotate.IntValue + 90) % 360;
page.Put(PdfName.ROTATE, new PdfNumber(rotation));
}
//获取PDFsize
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(global::HelloTeamcenter.Properties.Resources.SY, iTextSharp.text.BaseColor.WHITE);
image.GrayFill = 20;//透明度,灰色填充
//水印的位置
image.SetAbsolutePosition((width - image.Width )/2, (height - image.Height )/2 );
PdfContentByte waterMarkContent = pdfStamper.GetUnderContent(i);
waterMarkContent.AddImage(image);
pdfStamper.Close();
pdfReader.Close();
}
}catch(System.Exception){
cadEditor.WriteMessage("转换PDF出现异常");
}
return pdfNewPath;
}
/// <summary>
/// 合成pdf文件
/// </summary>
/// <param name="fileList">文件名list</param>
/// <param name="outMergeFile">输出路径</param>
public static void mergePDFFiles(PrintFrame[] frames ,List<string> fileList, string outMergeFile)
{
if (fileList.Count == 1 )
{
File.Copy(fileList[0], outMergeFile,true);
return;
}
Spire.Pdf.PdfDocument outPdf = new Spire.Pdf.PdfDocument();
for (int i = 0; i < fileList.Count;i++ )
{
Spire.Pdf.PdfDocument inPdf = new Spire.Pdf.PdfDocument();
inPdf.LoadFromFile(fileList[i]);
Spire.Pdf.PdfPageBase page = outPdf.Pages.Add(inPdf.Pages[0].Size, new Spire.Pdf.Graphics.PdfMargins(0));
inPdf.Pages[0].CreateTemplate().Draw(page, new System.Drawing.PointF(0, 0));
}
outPdf.SaveToFile(outMergeFile);
/*
PdfReader reader;
// Rectangle rec = new Rectangle(1660, 1000);
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
for (int i = 0; i < fileList.Count; i++)
{
reader = new PdfReader(fileList[i]);
iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
page = pdf2.Pages.Add(pdf.Pages[i].Size, newPdfMargins(0));
cb.AddTemplate(newPage, 0,0);//,width, height);
}
}
document.Close();
* */
}
/// <summary>
/// 导出PDF
/// </summary>
/// <param name="frame">PDF路径</param>
/// <returns></returns>
public string CreatePdf(PrintFrame frame,int index) {
string pdfPath = "";
Database database = PrintDoc.Database;
//;
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
using (Transaction transaction = database.TransactionManager.StartTransaction())
{
short backgroundPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead);
PlotInfo plotInfo = new PlotInfo();
PlotInfoValidator plotInfoValidator = new PlotInfoValidator();
plotInfoValidator.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
{
using (PlotEngine plotEngine = PlotFactory.CreatePublishEngine())
{
// Create a Progrel.ass Dialog to provide info
// and allow thej user to cancel
using (PlotProgressDialog plotProcessDialog = new PlotProgressDialog(false, 1, true))
{
BlockTableRecord acBlkTblRec = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
Layout layout = (Layout)transaction.GetObject(acBlkTblRec.LayoutId, OpenMode.ForRead);
// We need a PlotSettings object
// based on the layout settings
// which we then customize
PlotSettings plotSetting= new PlotSettings(layout.ModelType);
plotSetting.CopyFrom(layout);
// The PlotSettingsValidator helps
// create a valid PlotSettings object
PlotSettingsValidator plotSettingValidator = PlotSettingsValidator.Current;
// We'll plot the extents, centered and
// scaled to fit
StringCollection stringCollection = plotSettingValidator.GetPlotStyleSheetList();
bool StyleSheetCheck = false;
foreach (string s in stringCollection)
{
if (string.Compare(s, "monochrome.ctb", true) == 0)
{
StyleSheetCheck = true;
}
}
plotSettingValidator.SetPlotConfigurationName(plotSetting, "DWG To PDF.pc5", frame.MediaName);
plotSettingValidator.SetPlotWindowArea(plotSetting, frame.PrintBound);
plotSettingValidator.SetPlotType(plotSetting, ZwSoft.ZwCAD.DatabaseServices.PlotType.Window);
if (!StyleSheetCheck)
{
plotSettingValidator.SetCurrentStyleSheet(plotSetting, "monochrome.stb");
}
else
{
plotSettingValidator.SetCurrentStyleSheet(plotSetting, "monochrome.ctb");
}
plotSettingValidator.SetPlotCentered(plotSetting, true);
if(frame.BKName.ToUpper().Equals("A4-S")){
plotSettingValidator.SetPlotRotation(plotSetting, PlotRotation.Degrees090);
cadEditor.WriteMessage("IS A4-S SET Degrees090 ");
}
plotSettingValidator.SetUseStandardScale(plotSetting, true);
plotSettingValidator.SetStdScaleType(plotSetting, StdScaleType.ScaleToFit);
// We need a PlotInfo object
// linked to the layout
plotInfo.Layout = acBlkTblRec.LayoutId;
// Make the layout we're plotting current
LayoutManager.Current.CurrentLayout = layout.LayoutName;
// We need to link the PlotInfo to the
// PlotSettings and then validate it
plotInfo.OverrideSettings = plotSetting;
plotInfoValidator.Validate(plotInfo);
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
plotProcessDialog.LowerPlotProgressRange = 0;
plotProcessDialog.UpperPlotProgressRange = 100;
plotProcessDialog.PlotProgressPos = 0;
// Let's start the plot, at last
plotProcessDialog.OnBeginPlot();
plotProcessDialog.IsVisible = true;
plotEngine.BeginPlot(plotProcessDialog, null);
pdfPath = String.Format("{0}\\{1}_{2}.pdf", System.Environment.GetEnvironmentVariable("TEMP").ToString(),"DWG_PDF_",index);
plotEngine.BeginDocument(plotInfo, PrintDoc.Name, null, 1, true, pdfPath);
// psv.SetPlotRotation(ps, DataSvr.PlotRotation.Degrees090);
// Which may contain multiple sheets
plotProcessDialog.StatusMsgString = "Plotting " + PrintDoc.Name.Substring(PrintDoc.Name.LastIndexOf("\\") + 1) +
" - sheet 1 of 1" ;
plotProcessDialog.OnBeginSheet();
plotProcessDialog.LowerSheetProgressRange = 0;
plotProcessDialog.UpperSheetProgressRange = 100;
plotProcessDialog.SheetProgressPos = 0;
PlotPageInfo ppi = new PlotPageInfo();
plotEngine.BeginPage(ppi, plotInfo, true, null);
plotEngine.BeginGenerateGraphics(null);
plotProcessDialog.SheetProgressPos = 50;
plotEngine.EndGenerateGraphics(null);
// Finish the sheet
plotEngine.EndPage(null);
plotProcessDialog.SheetProgressPos = 100;
plotProcessDialog.OnEndSheet();
// Finish the document
plotEngine.EndDocument(null);
// And finish the plot
plotProcessDialog.PlotProgressPos = 100;
plotProcessDialog.OnEndPlot();
plotEngine.EndPlot(null);
plotProcessDialog.Dispose();
}
if (File.Exists(pdfPath))
{
pdfPath = PdfTo90(pdfPath, frame);
}
}
}
else
{
PrintDoc.Editor.WriteMessage("\nAnother plot is in progress.");
}
Application.SetSystemVariable("BACKGROUNDPLOT", backgroundPlot);
transaction.Commit();
}
return pdfPath;
}
/// <summary>
/// 生成多个PDF
/// </summary>
/// <param name="pdfName"></param>
/// <returns></returns>
public string MultiSheetPlot2(String pdfName) {
string path = "";
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
PrintFrame[] frames = CheckModelSpaceTitle();
if (frames.Length < 1)
return "";
List<string> pdfNameList = new List<string>();
for (int i =0;i< frames.Length;i++)
{
PrintFrame frame =frames[i];
string pdfPath = CreatePdf(frame, i);
cadEditor.WriteMessage("pdfPath =>" + pdfPath + "\n");
pdfNameList.Add(pdfPath);
}
path = String.Format("{0}\\{1}.pdf", System.Environment.GetEnvironmentVariable("TEMP").ToString(), pdfName);
cadEditor.WriteMessage("pdfName =>" + path + "\n");
//合并PDF
mergePDFFiles( frames,pdfNameList,path);
return path;
}
public string MultiSheetPlot(String pdfName)
{
string path = "";
Database database = PrintDoc.Database;
//;
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
using (Transaction transaction = database.TransactionManager.StartTransaction())
{
short backgroundPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead);
PlotInfo plotInfo = new PlotInfo();
PlotInfoValidator plotInfoValidator = new PlotInfoValidator();
plotInfoValidator.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
// A PlotEngine does the actual plotting
// (can also create one for Preview)
if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
{
using (PlotEngine plotEngine = PlotFactory.CreatePublishEngine())
{
PrintFrame[] frames = CheckModelSpaceTitle();
// Create a Progrel.ass Dialog to provide info
// and allow thej user to cancel
using (PlotProgressDialog plotProcessDialog = new PlotProgressDialog(false, frames.Length, true))
{
int numSheet = 1;
if (frames.Length < 1)
return "";
foreach (PrintFrame frame in frames)
{
BlockTableRecord acBlkTblRec = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
Layout lo = (Layout)transaction.GetObject(acBlkTblRec.LayoutId, OpenMode.ForRead);
// We need a PlotSettings object
// based on the layout settings
// which we then customize
PlotSettings ps = new PlotSettings(lo.ModelType);
ps.CopyFrom(lo);
// The PlotSettingsValidator helps
// create a valid PlotSettings object
PlotSettingsValidator psv = PlotSettingsValidator.Current;
// We'll plot the extents, centered and
// scaled to fit
StringCollection cols = psv.GetPlotStyleSheetList();
bool StyleSheetCheck = false;
foreach (string s in cols)
{
if (string.Compare(s, "monochrome.ctb", true) == 0)
{
StyleSheetCheck = true;
}
}
psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", frame.MediaName);
psv.SetPlotWindowArea(ps, frame.PrintBound);
psv.SetPlotType(ps, ZwSoft.ZwCAD.DatabaseServices.PlotType.Window);
psv.SetPlotRotation(ps, DataSvr.PlotRotation.Degrees090);
if (!StyleSheetCheck)
psv.SetCurrentStyleSheet(ps, "monochrome.stb");
else
psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
psv.SetPlotCentered(ps, true);
psv.SetUseStandardScale(ps, true);
psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
// cadEditor.WriteMessage("Rooation=>>" + frame.Rotation);
// psv.SetPlotRotation(ps, DataSvr.PlotRotation.Degrees090);// frame.Rotation);
// We need a PlotInfo object
// linked to the layout
plotInfo.Layout = acBlkTblRec.LayoutId;
// Make the layout we're plotting current
LayoutManager.Current.CurrentLayout = lo.LayoutName;
// We need to link the PlotInfo to the
// PlotSettings and then validate it
plotInfo.OverrideSettings = ps;
plotInfoValidator.Validate(plotInfo);
if (numSheet == 1)
{
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
plotProcessDialog.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
plotProcessDialog.LowerPlotProgressRange = 0;
plotProcessDialog.UpperPlotProgressRange = 100;
plotProcessDialog.PlotProgressPos = 0;
// Let's start the plot, at last
plotProcessDialog.OnBeginPlot();
plotProcessDialog.IsVisible = true;
plotEngine.BeginPlot(plotProcessDialog, null);
// We'll be plotting a single document // Let's plot to file
path = PrintDoc.Name.ToUpper().Replace(".DWG", string.Format("{0}{1}", frame.BKName, ".PDF"));
//myPdfName
path = path.Substring(0, path.LastIndexOf('\\') + 1) + pdfName+"1.PDF";
plotEngine.BeginDocument(plotInfo, PrintDoc.Name, null, 1, true, path);
}
// psv.SetPlotRotation(ps, DataSvr.PlotRotation.Degrees090);
// Which may contain multiple sheets
plotProcessDialog.StatusMsgString = "Plotting " + PrintDoc.Name.Substring(PrintDoc.Name.LastIndexOf("\\") + 1) +
" - sheet " + numSheet.ToString() +
" of " + frames.Length.ToString();
plotProcessDialog.OnBeginSheet();
plotProcessDialog.LowerSheetProgressRange = 0;
plotProcessDialog.UpperSheetProgressRange = 100;
plotProcessDialog.SheetProgressPos = 0;
PlotPageInfo ppi = new PlotPageInfo();
plotEngine.BeginPage(ppi, plotInfo, frames.Length == numSheet, null);
plotEngine.BeginGenerateGraphics(null);
plotProcessDialog.SheetProgressPos = 50;
plotEngine.EndGenerateGraphics(null);
// Finish the sheet
plotEngine.EndPage(null);
plotProcessDialog.SheetProgressPos = 100;
plotProcessDialog.OnEndSheet();
numSheet++;
//Thread.Sleep(30000);
}
// Finish the document
plotEngine.EndDocument(null);
// And finish the plot
plotProcessDialog.PlotProgressPos = 100;
plotProcessDialog.OnEndPlot();
plotEngine.EndPlot(null);
plotProcessDialog.Dispose();
}
if (File.Exists(path))
{
if (PDFWatermark(path, path.Replace("1.PDF", ".pdf"), 0, 0, frames))
{
return path.Replace("1.PDF", ".pdf");
}
}
}
}
else
{
PrintDoc.Editor.WriteMessage("\nAnother plot is in progress.");
}
Application.SetSystemVariable("BACKGROUNDPLOT", backgroundPlot);
transaction.Commit();
}
return path;
}
// 检查是否存在边框
private PrintFrame[] CheckModelSpaceTitle()
{
Database acCurDb = PrintDoc.Database;
List<PrintFrame> lstFrame = new List<PrintFrame>();
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;
// Open the Block table record for read
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
BlockReference reference;
BlockTableRecordEnumerator enumbtr = acBlkTblRec.GetEnumerator();
while (enumbtr.MoveNext())
{
Entity entity = acTrans.GetObject(enumbtr.Current, OpenMode.ForRead) as Entity;
if (entity is BlockReference)
{
reference = entity as BlockReference;
//int i = m_Frame.BinarySearch(new PrintFrame() { BKName = reference.Name }, new FrameCompare());
int i = -1;
for (int j = 0; j < m_Frame.Count; j++)
{
if (string.Compare((m_Frame[j] as PrintFrame).BKName, reference.Name, true) == 0)
{
i = j;
break;
}
}
if (i > -1)
{
Extents2d e2dBound = new Extents2d(reference.Bounds.Value.MinPoint.X, reference.Bounds.Value.MinPoint.Y, reference.Bounds.Value.MaxPoint.X, reference.Bounds.Value.MaxPoint.Y);
(m_Frame[i] as PrintFrame).PrintBound = e2dBound;
PrintFrame frm = new PrintFrame();
frm.Clone((m_Frame[i] as PrintFrame));
cadEditor.WriteMessage("MinPoint=>" + reference.Bounds.Value.MinPoint.X + "|" + reference.Bounds.Value.MinPoint.Y);
cadEditor.WriteMessage("MaxPoint=>" + reference.Bounds.Value.MaxPoint.X + "|" + reference.Bounds.Value.MaxPoint.Y);
frm._X = reference.Bounds.Value.MaxPoint.X - reference.Bounds.Value.MinPoint.X;
frm._Y = reference.Bounds.Value.MaxPoint.Y - reference.Bounds.Value.MinPoint.Y;
lstFrame.Add(frm);
}
}
}
acTrans.Commit();
}
return lstFrame.ToArray();
}
public ZwSoft.ZwCAD.ApplicationServices.Document PrintDoc
{
get;
set;
}
public bool PDFWatermark(string inputfilepath, string outputfilepath, float top, float left,PrintFrame[] frames)
{
//throw new NotImplementedException();
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
Editor cadEditor = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
try
{
pdfReader = new PdfReader(inputfilepath);
int numberOfPages = pdfReader.NumberOfPages;
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
cadEditor.WriteMessage(String.Format("\nwidth = {0}/height = {1}\n",width, height));
pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
PdfContentByte waterMarkContent;
//global::HelloTeamcenter.Properties.Resources.SY.;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(global::HelloTeamcenter.Properties.Resources.SY,iTextSharp.text.BaseColor.WHITE);
//iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);
image.GrayFill = 20;//透明度,灰色填充
//image.Rotation//旋转
//image.RotationDegrees//旋转角度
//水印的位置
if (left <= 0)
{
left = (width /2- image.Width/2) + left;
}
image.SetAbsolutePosition(left, (height/2 - image.Height/2) - top);
//每一页加水印,也可以设置某一页加水印
for (int i = 1; i <= numberOfPages; i++)
{
PdfDictionary page = pdfReader.GetPageN(i); //reader.getPageN(i);
//iTextSharp.text.Rectangle pageSize = pdfReader.GetPageSize(i);
// float myW = pageSize.Right - pageSize.Left;
// float myH = pageSize.Top - pageSize.Bottom;
// cadEditor.WriteMessage(String.Format("W={0}/H={1}\n", myW, myH));
if (frames != null && frames.Length == numberOfPages && frames[i].BlockF.Equals("W"))
{
PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
int rotation = rotate == null ? 90 : (rotate.IntValue + 90) % 360;
page.Put(PdfName.ROTATE, new PdfNumber(rotation));
}
waterMarkContent = pdfStamper.GetUnderContent(i);
waterMarkContent.AddImage(image);
}
//strMsg = "success";
return true;
}
catch (System.Exception ex)
{
ex.Message.Trim();
return false;
}
finally
{
if (pdfStamper != null)
pdfStamper.Close();
if (pdfReader != null)
pdfReader.Close();
}
}
}
}